Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

index.js 97KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609
  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. // PB : TODO -- defaults for valuless arguments if passed.
  30. // Object.keys(processedArgs).forEach(a=>{
  31. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  32. // }
  33. // })
  34. var globSync = require('glob').sync;
  35. var ENV = Object.assign({}, process.env); // Shallow clone it.
  36. const { readdir } = require("fs").promises
  37. // Directory shallow walk and do perform on each dir.
  38. const dirs = async (perform, path) => {
  39. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  40. if (dir.isDirectory()) perform(dir)
  41. }
  42. }
  43. var getShellTask = (command, args, options) => {
  44. options = options || {}
  45. return () => {
  46. var p = nodeShellExec.apply(null, [command, args, Object.assign({
  47. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  48. }, options)
  49. ])
  50. if (options.ignorefailures) {
  51. return p.catch(e => {
  52. // Ignore. Not a major error.
  53. })
  54. }
  55. else return p;
  56. }
  57. }
  58. var callsheltask = (args) => { return () => { return nodeShellExec.apply(null, args) } }
  59. var callgitbashtask = (args) => { return () => {
  60. return nodeShellExec( `"${gitbash}"`, ['-c', `"${args[0]} ${args[1].join(' ')}"`], args[2]) }
  61. }
  62. var getTaskCheckExists = (command, options) => {
  63. options = options || {}
  64. return () => {
  65. var p = nodeShellExec.apply(null, ['where', [command]])
  66. if (options.ignorefailures) {
  67. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  68. return false;
  69. })
  70. }
  71. else return p.then(() => { return true });
  72. }
  73. }
  74. var getTaskWithElevation = function(tasdef){
  75. return ()=>{
  76. if (__isElevated) {
  77. return tasdef.elevatedpulltasks().then(()=>{
  78. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  79. fs.writeFileSync('run.done', 'success')
  80. }).catch(e=>{
  81. fs.writeFileSync('run.done', 'failure')
  82. });
  83. }
  84. else {
  85. // PB : TODO -- Rename op['runas'] to 'elevate'
  86. var __runasresult = null;
  87. return op['runas']().then((r) => { return __runasresult = r; })
  88. .catch((e) => {
  89. console.error(e)
  90. })
  91. .finally(() => {
  92. if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done')
  93. if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
  94. })
  95. }
  96. }
  97. }
  98. var getTaskWithoutElevation = function(tasdef){
  99. return ()=>{
  100. if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  101. else Promise.resolve(true)
  102. }
  103. }
  104. var gitops = {
  105. getdiscoverbranchcmd : function(repo){
  106. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  107. var cmd = [gitbash
  108. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  109. , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo + ' ' + parameters.join(' ') }]
  110. return cmd
  111. }
  112. }
  113. var getPullCmd = (repo, branch) => {
  114. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  115. // console.log(useGitPull)
  116. // var pullCmd = [gitInstallDir
  117. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  118. // , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo }]
  119. if(branch) {
  120. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  121. var pullCmd = [ gitbash
  122. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  123. , { cwd: instanceroot + '/' + repo, title : 'pull all origins for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  124. }
  125. else {
  126. // console.warn('No branch was specified detecting from working client.')
  127. // First check if working client exits.
  128. // if (existsSync(instanceroot + '/' + repo)) {
  129. var pullCmd = gitops.getdiscoverbranchcmd(repo)
  130. // }
  131. // else performpull
  132. }
  133. // var pullCmd = ['pullall', [], { cwd : repo }]
  134. if (useGitPull) pullCmd = ['git', ['pull'], {
  135. inherit: true, shell: true,
  136. cwd: instanceroot + '/' + repo
  137. // , env: process.env
  138. , runas: processedArgs.runas
  139. , title: `git pull ${repo}`
  140. }]
  141. return pullCmd
  142. }
  143. var performPull = (repo, branch) => {
  144. // PB : TODO -- Handle no branch passed in case.
  145. // if(!branch) { throw 'No branch specified' }
  146. if (existsSync(instanceroot + '/' + repo)) {
  147. var branchprint = branch ? ' branch :' + branch : '';
  148. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  149. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  150. if (__isElevated) {
  151. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  152. }
  153. else statuslog.statuslog(null, repo)
  154. return true;
  155. })
  156. .catch((e) => {
  157. e.repo = repo;
  158. if (__isElevated) {
  159. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  160. }
  161. else statuslog.statuslog(e); console.error(e)
  162. })
  163. }
  164. else {
  165. console.log('cloning ' + repo)
  166. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  167. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'],
  168. {
  169. inherit: true, shell: true,
  170. env: process.env
  171. , cwd : instanceroot
  172. , runas: processedArgs.runas
  173. }).catch((e) => {
  174. throw e;
  175. }).then(() => {
  176. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  177. {
  178. inherit: true, shell: true,
  179. env: process.env
  180. , cwd: instanceroot + '/' + repo
  181. , runas: processedArgs.runas
  182. , title: `git core.symlinks --replace-all true for ${selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'}`
  183. })
  184. .then(() => {
  185. if (__isElevated) {
  186. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  187. }
  188. else statuslog.statuslog(null, repo)
  189. })
  190. .catch((e) => {
  191. e.repo = repo;
  192. if (__isElevated) {
  193. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  194. }
  195. else statuslog.statuslog(e);
  196. })
  197. })
  198. .catch(e => {
  199. e.repo = repo;
  200. if (__isElevated) {
  201. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  202. }
  203. else statuslog.statuslog(e);
  204. })
  205. }
  206. }
  207. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  208. // -- Currently workaround is to always run from a non-elevated shell.
  209. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  210. var acquireElevationState = () => {
  211. if (__isElevated === null) {
  212. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  213. inherit: true
  214. // , shell: true
  215. , stdio: 'ignore'
  216. , env: process.env
  217. , title: `check privileged execution mode using "fsutil dirty query C:"`
  218. }).then((exitcode) => {
  219. console.log('Elevated')
  220. __isElevated = true;
  221. return true;
  222. }).catch(() => {
  223. __isElevated = false;
  224. console.log('Not Elevated');
  225. return false;
  226. });
  227. }
  228. else return Promise.resolve(__isElevated);
  229. }
  230. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current gittea username
  231. var defaultRepoOwner = 'chess';
  232. var elevatedRunasRepos = null
  233. var gitRepos = null
  234. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  235. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  236. var dbForLabel = function (label) {
  237. var dbsForLabel = {
  238. devmysql: 'mysql'
  239. , development: 'mssql'
  240. , production: 'mssql'
  241. }
  242. return dbsForLabel[label] || 'mysql'
  243. }
  244. // SAM : TODO Use nodeshellexec where to detect git installation dir
  245. var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe"
  246. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  247. // Relevant git repos
  248. var exludeMergeRepos = [];
  249. var useGitPull = processedArgs.useGitPull || false;
  250. var configPromise = null
  251. // elxr cli operations
  252. var op = {
  253. 'h': () => { console.log(elxr.help()); return '-h' }
  254. , 'clean' : () => {
  255. // delete all node_module folders and links.
  256. var tasklist = [];
  257. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot )
  258. return Promise.all(tasklist)
  259. }
  260. , 'undefined': () => { return op.h(); }
  261. , 'reset': () => {
  262. // Reset NPM packages semver so major versions can be updated.
  263. const fs = require('fs')
  264. const wipeDependencies = (__package) => {
  265. const file = fs.readFileSync(__package + '/package.json')
  266. const content = JSON.parse(file)
  267. for (var devDep in content.devDependencies) {
  268. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  269. content.devDependencies[devDep] = '*';
  270. }
  271. }
  272. for (var dep in content.dependencies) {
  273. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  274. content.dependencies[dep] = '*';
  275. }
  276. }
  277. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  278. }
  279. var repos = ['client'];
  280. // repos = gitRepos;
  281. repos.forEach(wipeDependencies)
  282. // if (require.main === module) {
  283. // } else {
  284. // module.exports = wipeDependencies
  285. // }
  286. }
  287. , 'upgrade': () => {
  288. console.log('upgrade.......')
  289. var tasks = [
  290. () => {
  291. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  292. inherit: true, shell: true
  293. , env: process.env
  294. }).catch((e) => { console.error(e) })
  295. p.position = 1;
  296. console.log('One')
  297. return p;
  298. }
  299. , () => {
  300. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  301. inherit: true, shell: true
  302. , env: process.env
  303. }).catch((e) => { console.error(e) })
  304. p.position = 2;
  305. console.log('Two')
  306. return p;
  307. }
  308. , () => {
  309. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  310. inherit: true, shell: true
  311. , env: process.env
  312. }).catch((e) => { console.error(e) })
  313. p.position = 3;
  314. console.log('Three')
  315. return p;
  316. }
  317. , () => {
  318. var p = nodeShellExec('n', ['latest'], {
  319. inherit: true, shell: true
  320. , env: process.env
  321. }).catch((e) => { console.error(e) })
  322. p.position = 4;
  323. console.log('Four')
  324. return p;
  325. }
  326. ]
  327. any(tasks)
  328. console.log('.......done')
  329. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  330. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  331. console.info('Uninstalling existing ember globally');
  332. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  333. stdio: ['pipe', process.stdout, process.stderr],
  334. inherit: true,
  335. shell: true,
  336. cwd: path.dirname(__dirname),
  337. env: env
  338. })
  339. step1.on('close', () => {
  340. console.info('Installing ember globally');
  341. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  342. stdio: ['pipe', process.stdout, process.stderr],
  343. inherit: true,
  344. shell: true,
  345. cwd: path.dirname(__dirname),
  346. env: env
  347. })
  348. step2.on('close', () => {
  349. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  350. stdio: ['pipe', process.stdout, process.stderr],
  351. inherit: true,
  352. shell: true,
  353. cwd: path.dirname(__dirname),
  354. env: env
  355. })
  356. })
  357. })
  358. }
  359. , 'runas': () => {
  360. if(processedArgs.skipelevated) return Promise.resolve({ skipped : true });
  361. console.log('Testing Elevation')
  362. if (__isElevated) {
  363. try {
  364. op[processedArgs.label || processedArgs._[0] || 'h']()
  365. }
  366. catch (e) {
  367. console.error('Error Invalid command : ' + e)
  368. fs.writeFileSync('run.done', 'error')
  369. }
  370. finally {
  371. }
  372. }
  373. else {
  374. console.log('Requesting Elevated Privileges');
  375. // Wait for the runas to complete before we read it.
  376. try {
  377. fs.unlinkSync('run.done')
  378. fs.unlinkSync('run.log')
  379. }
  380. catch (e) { } //Ignore
  381. // Find node path to send to hta.
  382. return nodeShellExec('where', ['node']).then(r => {
  383. var namedArgs = [];
  384. console.log('result : ' + JSON.stringify(r))
  385. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; })
  386. // PB : TODO -- Convert all the cli args back to string.
  387. var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  388. args.push('--nodepath=' + r[r.length - 1])
  389. if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
  390. if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
  391. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  392. , {
  393. inherit: true
  394. , shell: true
  395. , env: ENV
  396. , runas: 'self'
  397. , title: `runas`
  398. }
  399. ).then(() => {
  400. // runas returned.
  401. try {
  402. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  403. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  404. runaslog.forEach((logEntry) => {
  405. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry)
  406. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  407. })
  408. }
  409. catch (e) {
  410. // We must have a runas log
  411. statuslog.statuslog(e)
  412. console.error('Run log error probably was not created by runas : ' + e)
  413. }
  414. })
  415. .catch(err => console.error('Elevation failed : ' + err));
  416. })
  417. }
  418. }
  419. , 'push': () => {
  420. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  421. // init remote bare from local
  422. // pushandinitremotebare
  423. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  424. // connect to repo server -- net use 172.16.0.27
  425. // cd 172.16.0.27/repos/
  426. // mkdir repo.git
  427. // cd repo.git
  428. // git init --bare
  429. // cd localrepo
  430. // git remote rename origin githubclone
  431. // git remote add origin //172.16.0.27/repos/repo.git
  432. // git push origin master
  433. var repo = processedArgs._[1];
  434. var sequentialTaskShellCommands = [];
  435. if (!existsSync(`Z:/${repo}.git`)) {
  436. sequentialTaskShellCommands = [
  437. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  438. // inherit : true, shell: true
  439. // , env: process.env
  440. // }]
  441. ['pwd', { cwd: 'Z:', inherit: true }]
  442. , ['mkdir', [`${repo}.git`], {
  443. cwd: `Z:`
  444. , inherit: true, shell: true
  445. , env: process.env
  446. }]
  447. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  448. , ['git', ['init', '--bare'], {
  449. cwd: `Z:/${repo}.git`
  450. , inherit: true, shell: true
  451. , env: process.env
  452. }]
  453. // PB : TODO -- Do this conditionally only...
  454. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  455. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  456. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  457. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  458. // PB : TODO -- If threre is a gitbubclone origin
  459. // Set the master to pull from the local repo.
  460. ]
  461. if (!existsSync(`Z:`)) {
  462. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  463. inherit: true, shell: true
  464. , env: process.env
  465. }])
  466. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  467. // throw 'done'
  468. }
  469. }
  470. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }])
  471. // console.dir(sequentialTaskShellCommands);
  472. var tasks = [];
  473. sequentialTaskShellCommands.forEach(shellcmd => {
  474. // console.log(shellcmd)
  475. tasks.push(() => {
  476. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
  477. return p;
  478. })
  479. })
  480. any(tasks);
  481. }
  482. , 'is-git-repo': (dir) => {
  483. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  484. }
  485. // git remote equivalents...
  486. // git branch --set-upstream-to=elixir-unc/master master
  487. // git push --set-upstream elixir-unc branch..
  488. , 'remote': (args) => {
  489. // Subcommands!
  490. if(!processedArgs.v) return false; // Only -v is supported presently..
  491. var serial_perform = (repo) => {
  492. var options = { cwd: instanceroot + '/' + repo }
  493. return [
  494. ['git', ['remote', '-v'], options]
  495. ]
  496. }
  497. var x = (args) => {
  498. var tasq = () => {
  499. // console.log(args)
  500. return nodeShellExec.apply(null, args).catch(e => {
  501. // We continue on failure.
  502. console.error(tasq.toString())
  503. })
  504. }
  505. tasq.toString = function(){
  506. return JSON.stringify(args)
  507. }
  508. return tasq;
  509. }
  510. var perform = (dir) => {
  511. return any(serial_perform(dir.name).map(x))
  512. }
  513. dirs(perform)
  514. }
  515. , 'remote set-url': (args) => {
  516. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  517. var __args = {
  518. remotename : args.remotename || processedArgs._[2]
  519. , url : args.url || processedArgs._[3]
  520. }
  521. // pushable doesn't mean the remote doesn't support being pushed to.
  522. // Over here it just means we are disabling pushing to that remote by setting the push portion of the url the a junk remote called no-pushing.
  523. // PB : TODO -- change this to enablepushing.
  524. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  525. var pushable = processedArgs.pushable || false;
  526. remotename = __args.remotename
  527. url = __args.url
  528. var serial_perform_git_seturl = (repo) => {
  529. var options = { cwd: instanceroot + '/' + repo }
  530. // console.log(repo)
  531. if (pushable) {
  532. return [
  533. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  534. , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  535. ]
  536. }
  537. else {
  538. return [
  539. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  540. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  541. ]
  542. }
  543. }
  544. var x = (args) => {
  545. var tasq = () => {
  546. // console.log(args)
  547. return nodeShellExec.apply(null, args).catch(e => {
  548. // We continue on failure.
  549. console.error(tasq.toString())
  550. })
  551. }
  552. tasq.toString = function(){
  553. return JSON.stringify(args)
  554. }
  555. return tasq;
  556. }
  557. var perform_git_seturl = (dir) => {
  558. op['is-git-repo'](dir).then((logEntry) => {
  559. return any(serial_perform_git_seturl(dir.name).map(x))
  560. }).catch((e) => {
  561. // console.log('Failed : ' + dir.name)
  562. })
  563. }
  564. dirs(perform_git_seturl)
  565. }
  566. , 'reset' : ()=>{
  567. // Reset the whole installation pertaining to this elxr folder.
  568. }
  569. , 'add': (remotename, url, branch) => {
  570. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  571. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  572. // That explicitly has a remote name prefix.
  573. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  574. // git branch branch_name -u your_new_remote/branch_name -- older versions
  575. // git branch -vv -- Detect which branch are we tracking.
  576. // default upstream should be users own fork.
  577. // Also need alias branches to
  578. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  579. // probably git merge from all remotes... and relevant branches...
  580. // alias pushall='for i in `git remote`; do git push $i; done;'
  581. // alias pullall='for i in `git remote`; do git pull $i; done;'
  582. var pushable = processedArgs.pushable || false;
  583. remotename = remotename || processedArgs._[1]
  584. url = url || processedArgs._[2]
  585. branch = branch || processedArgs._[3]
  586. var serial_perform_git_add = (repo) => {
  587. var options = { cwd: instanceroot + '/' + repo }
  588. // console.log(repo)
  589. if (pushable) {
  590. return [
  591. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  592. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  593. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  594. ]
  595. }
  596. else {
  597. return [
  598. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  599. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  600. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  601. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  602. ]
  603. }
  604. }
  605. var x = (args) => {
  606. return () => {
  607. // console.log(args)
  608. return nodeShellExec.apply(null, args)
  609. }
  610. // return Promise.resolve(true)
  611. }
  612. var perform_git_add = (dir) => {
  613. op['is-git-repo'](dir).then((logEntry) => {
  614. // console.log(code)
  615. if (logEntry.success) {
  616. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  617. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  618. })
  619. .catch((e) => {
  620. any(serial_perform_git_add(dir.name).map(x))
  621. })
  622. }
  623. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  624. }).catch((e) => {
  625. // console.log('Failed : ' + dir.name)
  626. })
  627. }
  628. const { readdir } = require("fs").promises
  629. dirs(perform_git_add)
  630. }
  631. , 'remote remove': (args) => {
  632. var __args = {
  633. remotename : args.remotename|| processedArgs._[2]
  634. }
  635. var remotename = __args.remotename
  636. var serial_perform_git_remove = (repo) => {
  637. var options = { cwd: instanceroot + '/' + repo }
  638. // console.log(repo)
  639. return [
  640. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  641. ]
  642. }
  643. var x = (args) => {
  644. return () => {
  645. // console.log(args)
  646. return nodeShellExec.apply(null, args)
  647. }
  648. // return Promise.resolve(true)
  649. }
  650. var perform_git_remove = (dir) => {
  651. op['is-git-repo'](dir).then((logEntry) => {
  652. // console.log(code)
  653. if (logEntry.success) {
  654. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  655. any(serial_perform_git_remove(dir.name).map(x))
  656. })
  657. .catch((e) => {
  658. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`)
  659. })
  660. }
  661. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  662. }).catch((e) => {
  663. // console.log('Failed : ' + dir.name)
  664. })
  665. }
  666. const { readdir } = require("fs").promises
  667. dirs(perform_git_remove)
  668. }
  669. , 'init-gitea': (user) => {
  670. user = user || processedArgs._[1]
  671. if (!user) throw 'User name required'
  672. var serial_perform_init_gitea = (repo) => {
  673. var options = { cwd: instanceroot + '/' + repo }
  674. // console.log(repo)
  675. return [
  676. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  677. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  678. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  679. ]
  680. }
  681. var x = (args) => {
  682. return () => {
  683. // console.log(args)
  684. return nodeShellExec.apply(null, args)
  685. }
  686. // return Promise.resolve(true)
  687. }
  688. var perform_init_gitea = (dir) => {
  689. op['is-git-repo'](dir).then((logEntry) => {
  690. // console.log(code)
  691. if (logEntry.success) {
  692. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  693. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  694. })
  695. .catch((e) => {
  696. any(serial_perform_init_gitea(dir.name).map(x))
  697. })
  698. }
  699. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  700. }).catch((e) => {
  701. // console.log('Failed : ' + dir.name)
  702. })
  703. }
  704. const { readdir } = require("fs").promises
  705. dirs(perform_init_gitea)
  706. }
  707. , 'syncmaster': (label) => {
  708. // Usage :
  709. // elxr pull -- Defaults to run config
  710. var env = Object.assign({}, process.env); // Shallow clone it.
  711. // console.dir(env)
  712. console.log('Running exlr pull : ' + path.dirname(__dirname))
  713. if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'))
  714. if (__isElevated) {
  715. return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
  716. fs.writeFileSync('run.done', 'success')
  717. }).catch(() => {
  718. fs.writeFileSync('run.done', 'error')
  719. })
  720. }
  721. else return op['runas']()
  722. }
  723. , 'repo-relocate' : function(args){
  724. // relocate a subfolder in source repo to same subfolder in target repo with history.
  725. var args = args || {
  726. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  727. , folder : processedArgs._[3] || 'server'
  728. , sourcerepo : processedArgs._[2] || 'client'
  729. , targetrepo : processedArgs._[1] || 'elixir-server'
  730. }
  731. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  732. // , stdio: ['pipe', process.stdout, process.stderr]
  733. , inherit: true,
  734. shell: true,
  735. env: process.env
  736. , runas: processedArgs.runas
  737. }
  738. return op['repo-split'](args).then(()=>{
  739. return op['repo-merge'](args).then(()=>{
  740. // cleanup folder from source.
  741. var cmdseq = [
  742. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  743. // commits have to intentional...
  744. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  745. ]
  746. return any(cmdseq.map(callsheltask))
  747. })
  748. }).catch(e=>{console.error(e)})
  749. }
  750. , 'repo-split' : function(args) {
  751. // https://gist.github.com/smdabdoub/17065c348289158277b5
  752. /**
  753. * Eg : folder, remotebase, sourcerepo, targetrepo
  754. * args.folder = 'server'
  755. * args.remotebase = 'https://git.bbh/chess/'
  756. * args.sourcerepo = 'client'
  757. * args.targetrepo = 'elixir-server'
  758. */
  759. var args = args || {
  760. folder : 'server'
  761. , remotebase : 'http://git.bbh/chess/'
  762. , sourcerepo : 'client'
  763. , targetrepo : 'elixir-server'
  764. }
  765. var options = { cwd: `${instanceroot}/relocate`
  766. // , stdio: ['pipe', process.stdout, process.stderr]
  767. , inherit: true,
  768. shell: true,
  769. env: process.env
  770. , runas: processedArgs.runas
  771. }
  772. var cmdseq = [
  773. // create a temporary working dir in current folder where we started execution.
  774. ['mkdir', [ '-p', 'relocate']]
  775. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  776. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  777. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  778. ]
  779. return any(cmdseq.map(callsheltask)).then(() => {
  780. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  781. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  782. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  783. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  784. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  785. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  786. // subtree split and filter-branch are options. We currently use repo-filter.
  787. return op['filter-repo'](args)
  788. }).catch(e=>{console.error(e); throw 'failed'})
  789. }
  790. , 'repo-merge' : function(args) {
  791. // Merge source repo into target repo
  792. var args = args || {
  793. folder : 'server'
  794. , remotebase : 'http://git.bbh/chess/'
  795. , sourcerepo : 'client'
  796. , targetrepo : 'elixir-server'
  797. }
  798. var sourcerepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  799. // , stdio: ['pipe', process.stdout, process.stderr]
  800. , inherit: true,
  801. shell: true,
  802. env: process.env
  803. , runas: processedArgs.runas
  804. }
  805. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  806. // , stdio: ['pipe', process.stdout, process.stderr]
  807. , inherit: true,
  808. shell: true,
  809. env: process.env
  810. , runas: processedArgs.runas
  811. }
  812. var cmdseq = [
  813. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  814. , targetrepooptions ]
  815. // , ['git', ['push', targetrepooptions ] // manual push for now..
  816. ]
  817. return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e)})
  818. }
  819. , 'filter-repo' : function(args){
  820. // Merge source repo into target repo
  821. var args = args || {
  822. folder : 'server'
  823. , remotebase : 'http://git.bbh/chess/'
  824. , targetrepo : 'elixir-server'
  825. }
  826. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  827. , inherit: true, shell: true
  828. , env: process.env
  829. , runas: processedArgs.runas
  830. }
  831. var cmdseq = [
  832. // git checkout -b feature/merge-old-project
  833. // git remote add src-project ../src-project
  834. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  835. ]
  836. return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e); throw 'failed' })
  837. }
  838. , 'filter-branch' : function(preservefolder, repo){
  839. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  840. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  841. // Preserve a specific folder.
  842. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  843. /*
  844. git clone repo reposplit
  845. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  846. git remote rm origin
  847. */
  848. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  849. }
  850. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  851. // // Merge repo2 into a subfolder in repo1
  852. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  853. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  854. // /*
  855. // cd repo1
  856. // git remote add -f tempmergesource ../{{mergesource}}/.git
  857. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  858. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  859. // git commit
  860. // // Repair History
  861. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  862. // #!/usr/bin/env bash
  863. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  864. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  865. // subdir=server
  866. // git filter-branch --tree-filter '
  867. // first='"$first"'
  868. // last='"$last"'
  869. // subdir='"$subdir"'
  870. // log_file=/tmp/filter.log
  871. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  872. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  873. // echo "=== $GIT_COMMIT: making changes"
  874. // files=$(git ls-tree --name-only $GIT_COMMIT)
  875. // mkdir -p $subdir
  876. // for i in $files; do
  877. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  878. // done
  879. // else
  880. // echo "=== $GIT_COMMIT: ignoring"
  881. // fi \
  882. // >> $log_file
  883. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  884. // status=0 # tell tree-filter never to fail
  885. // '
  886. // git remote rm tempmergesource
  887. // */
  888. // // better alternative for history
  889. // /**
  890. // *
  891. // git clone git@server.com:old-project.git
  892. // git clone git@server.com:new-project.git
  893. // cd old-project
  894. // mkdir old-project
  895. // git mv !(old-project) old-project
  896. // ls -la and gt mv hidden files ....
  897. // git commit -a -S -m “Moving old project into its own subdirectory”
  898. // cd ../new-project
  899. // git remote add old-project ../old-project
  900. // git fetch old-project
  901. // git checkout -b feature/merge-old-project
  902. // git merge -S --allow-unrelated-histories old-project/master
  903. // git push origin feature/merge-old-project
  904. // git remote rm old-project
  905. // */
  906. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  907. // }
  908. , 'pull' : (label) => {
  909. // Usage :
  910. // elxr pull -- Defaults to run config
  911. return elxr.getpulltask(selectedinstance)()
  912. }
  913. , 'isInstalled': () => {
  914. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  915. console.log(processedArgs._[1] + ' exists.')
  916. return true;
  917. });
  918. }
  919. , 'i' : () => {
  920. var tasks = []
  921. // tasks.push(op['pull']);
  922. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
  923. tasks.push(op['use'])
  924. if (!__isElevated) {
  925. tasks.push(op['npmi'])
  926. }
  927. // var tasksdefs = [
  928. // ['elxr', ['pull']]
  929. // , ['elxr', ['use', 'elixir']]
  930. // , ['elxr', ['npmi']]
  931. // ]
  932. // tasksdefs.forEach(tasksdef=>{
  933. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  934. // })
  935. return any(tasks);
  936. }
  937. , 'npmi': () => {
  938. var tasks = [];
  939. // Build fails without babel...
  940. tasks.push(getShellTask(
  941. 'npm',[ 'i', '-g', 'babel-cli' ]
  942. ) )
  943. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  944. npmbuildrepos = []
  945. npmbuildrepos.forEach(repo => {
  946. tasks.push(() => {
  947. return nodeShellExec('npm', ['i --force'], {
  948. inherit: true, shell: true
  949. , cwd: instanceroot + '/' + repo
  950. , env: process.env
  951. , title: `npm i for ${repo}`
  952. }).catch((e) => {
  953. console.error('Ignoring Benign Error'); console.error(e);
  954. }).then(() => {
  955. console.log(`--npm run build for ${repo}--------------------`)
  956. return nodeShellExec('npm', ['run build'], {
  957. inherit: true, shell: true
  958. , cwd: instanceroot + '/' + repo
  959. , env: process.env
  960. , title: `npm run build for ${repo}`
  961. }).then(Tasq.then).catch(Tasq.catch)
  962. })
  963. })
  964. })
  965. any(tasks).then(() => {
  966. gitRepos.push('client/server');
  967. gitRepos = gitRepos.concat(elevatedRunasRepos);
  968. // gitRepos = [
  969. // // 'bbhverse', 'serververse', 'elixir-server',
  970. // // 'clientverse',
  971. // 'client'
  972. // ];
  973. var rmtasks = []
  974. var repotasks = []
  975. var env = Object.assign({}, process.env)
  976. delete env.NODE_ENV
  977. gitRepos.forEach(repodef => {
  978. rmtasks.push(
  979. // () => {
  980. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  981. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  982. nodeShellExec('rm', ['package-lock.json'], {
  983. inherit: true, shell: true
  984. , cwd: instanceroot + '/' + repodef.repo
  985. , env: process.env
  986. , title: `rm 'package-lock.json' for ${repodef.repo}`
  987. })
  988. .then(()=>{
  989. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  990. }).catch((e) => { console.error(e) })
  991. // }
  992. )
  993. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  994. repotasks.push(
  995. () => {
  996. console.log(`--npm i for ${repodef.repo}--------------------`)
  997. var p = nodeShellExec('npm', ['i', '--force'], {
  998. inherit: true, shell: true
  999. , cwd: instanceroot + '/' + repodef.repo
  1000. , env
  1001. , title: `npm i for ${repodef.repo}`
  1002. }).then(Tasq.then).catch(Tasq.catch)
  1003. return p;
  1004. })
  1005. }
  1006. })
  1007. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  1008. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  1009. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  1010. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  1011. // Second time try also doesnt work.
  1012. // repotasks.push(
  1013. // () => {
  1014. // var env = Object.assign({}, process.env)
  1015. // delete env.NODE_ENV
  1016. // console.log(`--------------------second time npm i for client--------------------`)
  1017. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  1018. // // return nodeShellExec('npm', ['i --force'], {
  1019. // inherit: true, shell: true
  1020. // , cwd: instanceroot + '/' + 'client'
  1021. // , env
  1022. // , title: `npm i for client`
  1023. // }).then(Tasq.then).catch(Tasq.catch)
  1024. // })
  1025. var bowerRepos = [{ repo : 'client'}]
  1026. bowerRepos.forEach(repodef => {
  1027. repotasks.push(() => {
  1028. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
  1029. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  1030. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  1031. inherit: true, shell: true
  1032. , cwd: instanceroot + '/' + repodef.repo
  1033. , env: process.env
  1034. , title: `bower i for ${repodef.repo}`
  1035. }).then(Tasq.then).catch(Tasq.catch)
  1036. return p;
  1037. })
  1038. })
  1039. // console.log('rmtasks.length : ' + rmtasks.length)
  1040. return Promise.all(rmtasks).then(() => any(repotasks));
  1041. }).catch(e => {
  1042. }).finally(statuslog.finally)
  1043. }
  1044. , 'start': (label) => {
  1045. console.log('Starting Elixir Server.');
  1046. var env = Object.assign({}, process.env); // Shallow clone it.
  1047. // console.dir(env)
  1048. env.NODE_ENV = process.env.NODE_ENV || 'development';
  1049. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  1050. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  1051. // cmd = 'node'
  1052. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
  1053. var childPromise = nodeShellExec(...cmd, {
  1054. // inherit : true,
  1055. shell: true,
  1056. detached: true,
  1057. stdio: 'ignore',
  1058. cwd: instanceroot + '/' + 'elixir-server'
  1059. , env: env
  1060. })
  1061. var child = childPromise.process;
  1062. if (typeof child.pid !== 'undefined') {
  1063. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1064. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  1065. encoding: 'utf8'
  1066. })
  1067. }
  1068. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  1069. // inherit : true,
  1070. // shell: true, detached: true,
  1071. // cwd : 'qms/server',
  1072. // env: env,
  1073. // shell : true
  1074. // })
  1075. // nodeShellExec('ember', ['s'], {
  1076. // // inherit : true,
  1077. // shell: true, detached: true,
  1078. // cwd : 'client/',
  1079. // env: env
  1080. // })
  1081. console.log('Starting Elixir Client Host.');
  1082. var cmd = ['ember', ['s']]
  1083. var childPromise = nodeShellExec(...cmd, {
  1084. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  1085. // PB : TODO -- ember debugging.
  1086. // inherit : true,
  1087. shell: true,
  1088. detached: true,
  1089. stdio: 'ignore',
  1090. cwd: instanceroot + '/' + 'client'
  1091. , env: env
  1092. })
  1093. // .catch(e=>console.error(e))
  1094. child = childPromise.process;
  1095. if (typeof child.pid !== 'undefined') {
  1096. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1097. fs.writeFileSync('.client.server.pid', child.pid, {
  1098. encoding: 'utf8'
  1099. })
  1100. }
  1101. }
  1102. , 'stop': (label) => {
  1103. const kill = require('tree-kill');
  1104. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  1105. encoding: 'utf8'
  1106. })
  1107. fs.unlinkSync('.elixir-server.elixir.server.pid')
  1108. console.log(serverPid)
  1109. kill(serverPid)
  1110. serverPid = fs.readFileSync('.client.server.pid', {
  1111. encoding: 'utf8'
  1112. })
  1113. fs.unlinkSync('.client.server.pid')
  1114. console.log(serverPid)
  1115. kill(serverPid)
  1116. }
  1117. , 'model' : () => {
  1118. if (__isElevated) {
  1119. var tasks = [
  1120. () => {
  1121. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  1122. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  1123. inherit: true, shell: true
  1124. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  1125. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  1126. , env: process.env
  1127. }).catch((e) => { console.error(e) })
  1128. return p;
  1129. }
  1130. ];
  1131. return any(tasks).then(() => {
  1132. fs.writeFileSync('run.done', 'success')
  1133. }).catch(() => {
  1134. fs.writeFileSync('run.done', 'error')
  1135. })
  1136. }
  1137. else return op['runas']()
  1138. }
  1139. , 'use' : () => {
  1140. // use a certain named instance.
  1141. // Eg :
  1142. // 1) elxr use elixir
  1143. // 2) elxr use cihsr
  1144. // If environment is not specified defaults to development.
  1145. // 1) NODE=test elxr use elixir
  1146. /*// Steps
  1147. 1) Delete Config and Data symlinks
  1148. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  1149. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  1150. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1151. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  1152. */
  1153. var runconfig = { NODE_ENV: selectedinstance.node_env }
  1154. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  1155. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  1156. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  1157. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  1158. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  1159. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  1160. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  1161. return
  1162. }
  1163. var tasks = [
  1164. () => {
  1165. if (existsSync('config')) {
  1166. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  1167. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  1168. return p;
  1169. }
  1170. else return Promise.resolve(true);
  1171. },
  1172. () => {
  1173. if (existsSync('data')) {
  1174. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  1175. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  1176. return p;
  1177. }
  1178. else return Promise.resolve(true);
  1179. },
  1180. ];
  1181. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  1182. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  1183. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  1184. // console.log(process.env.cwd)
  1185. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  1186. // Maps an environment to a branch. Not required if the branch is appropriately named.
  1187. var checkoutMap = { 'development': 'master' }
  1188. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  1189. var performPullOrCloneForBranch = (def)=>{
  1190. var promise = Promise.resolve(true)
  1191. if (!branch) {
  1192. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1193. promise = nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{ branch = __branch})
  1194. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1195. }
  1196. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e )})
  1197. }
  1198. var performCloneAndCheckout = null;
  1199. // cant use git checkout -b it fails when branch already exists.
  1200. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1201. return performPullOrCloneForBranch(def).then(()=>{
  1202. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1203. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1204. // inherit : true, shell: true,
  1205. cwd: instanceroot + '/' + def.repo
  1206. // , stdio : ignore // Use when we want to silence output completely.
  1207. , runas: processedArgs.runas
  1208. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  1209. }).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 } })
  1210. })
  1211. }
  1212. // var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  1213. // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  1214. var elevatedqueue = [];
  1215. var enqueueOnce = (queue, task, def) => {
  1216. var found = queue.find(element => {
  1217. var keys = Object.keys( element )
  1218. for(var k=0; k < keys.length; k++) {
  1219. if(element[keys[k]] !== def[k]) return false;
  1220. }
  1221. })
  1222. queue.push(function(){ return task(this)}.bind(def));
  1223. }
  1224. var enqueue = (queue, task, def) => {
  1225. queue.push(function(){ return task(def)}.bind(def));
  1226. }
  1227. var mergeSources = {
  1228. 'development': null,
  1229. 'test': 'master',
  1230. 'production': 'master'
  1231. }
  1232. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1233. // Checkout is reduced to pull provided the current branch is the targetbranch
  1234. if(branch === mergesource) performCheckout = (def) => {
  1235. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1236. return nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{
  1237. if(branch === __branch) return performCloneAndCheckout(def)
  1238. return performPullOrCloneForBranch(def)
  1239. })
  1240. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1241. }
  1242. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  1243. var performPullAll = (def) => {
  1244. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1245. return nodeShellExec('git', ['pull', '--all'], {
  1246. // inherit : true, shell: true,
  1247. cwd: instanceroot + '/' + def.repo
  1248. , runas: processedArgs.runas
  1249. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  1250. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  1251. }
  1252. var excludeCheckouts = Object.assign(exludeMergeRepos)
  1253. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  1254. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  1255. var performMerge = (def) => {
  1256. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  1257. return nodeShellExec('git', ['merge', mergesource], {
  1258. inherit: true, shell: true,
  1259. cwd: instanceroot + '/' + def.repo
  1260. , runas: processedArgs.runas
  1261. }).catch((e) => { console.error(e) })
  1262. }
  1263. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
  1264. // var performRepoOperation = function(def) {
  1265. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  1266. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  1267. // }
  1268. return any(tasks).then(() => {
  1269. var pr = Promise.resolve(true)
  1270. if (!__isElevated) {
  1271. pr = op['runas']()
  1272. return pr.then(()=>{
  1273. //target is the env is we specify in elxr use command. Default is dev
  1274. //Switch to target branch
  1275. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  1276. // pull or clone target branch
  1277. .then(() => {
  1278. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1279. return any(gitRepos.map((repo) => performPullAll(repo)))
  1280. })
  1281. // switch to source branch
  1282. .then( () => {
  1283. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  1284. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  1285. })
  1286. //Pull on merge source branch
  1287. .then( () => {
  1288. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1289. return any(gitRepos.map((repo) => performPullAll(repo)))
  1290. })
  1291. //Switch to target branch
  1292. .then( () => {
  1293. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1294. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  1295. })
  1296. .then( //Merge source branch to target branch
  1297. () => {
  1298. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1299. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
  1300. })
  1301. })
  1302. }
  1303. else {
  1304. tasks = [
  1305. () => {
  1306. // Use junctions to avoid npm package issues
  1307. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  1308. inherit: true, shell: true
  1309. , cwd : instanceroot
  1310. , env: process.env
  1311. }).catch((e) => { console.error(e) })
  1312. return p;
  1313. }
  1314. ];
  1315. if (processedArgs._[1]) {
  1316. tasks = tasks.concat(
  1317. [
  1318. () => {
  1319. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  1320. inherit: true, shell: true
  1321. , cwd : instanceroot
  1322. , env: process.env
  1323. }).catch((e) => { console.error(e) })
  1324. return p;
  1325. }
  1326. ]
  1327. )
  1328. }
  1329. return any(tasks).then(()=>{
  1330. // checkout target branch
  1331. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1332. // pull or clone target branch
  1333. .then(() => {
  1334. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1335. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  1336. })
  1337. // switch to source branch
  1338. .then( () => {
  1339. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1340. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  1341. })
  1342. //Pull on merge source branch
  1343. .then( () => {
  1344. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1345. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  1346. })
  1347. //Switch to target branch
  1348. .then( () => {
  1349. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1350. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1351. })
  1352. .then( //Merge source branch to target branch
  1353. () => {
  1354. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1355. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
  1356. })
  1357. .then(() => {
  1358. fs.writeFileSync('run.done', 'success')
  1359. }).catch(() => {
  1360. fs.writeFileSync('run.done', 'error')
  1361. })
  1362. })
  1363. }
  1364. }).catch(() => {
  1365. fs.writeFileSync('run.done', 'error')
  1366. })
  1367. // Antibiotic stewardship program.
  1368. // 1st use is fine.
  1369. // Max vials dispense
  1370. // 2nd use Pharmacy needs justification Form.
  1371. // Approval after a certain period of time.
  1372. }
  1373. , 'g': () => {
  1374. if (processedArgs.h) {
  1375. console.log('elxr g [modelname] => generate a model named [modelname]');
  1376. console.log('elxr g => regenerate all known models');
  1377. return
  1378. }
  1379. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1380. // console.log('Starting directory: ' + process.cwd());
  1381. // try {
  1382. // child = child.on('close', () => { process.chdir(label) } );
  1383. // console.log('New directory: ' + process.cwd());
  1384. // }
  1385. // catch (err) {
  1386. // console.log('chdir: ' + err);
  1387. // }
  1388. // child.on('close', function(){
  1389. // var options = {
  1390. // shell : true
  1391. // , inherit : true
  1392. // // , cwd : '' + process.cwd
  1393. // // , env : process.env
  1394. // };
  1395. // nodeShellExec('git', ['init'], { inherit : true});
  1396. if (0) {
  1397. // PB : TODO -- Special google chrome profile for tests etc.
  1398. nodeShellExec('pwd', { inherit: true });
  1399. // /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"
  1400. // "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
  1401. // "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
  1402. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1403. "--profile-directory=Profile 1"
  1404. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1405. }
  1406. // nodeShellExec('npm', ['init', '-y'], options);
  1407. // nodeShellExec('npm', ['init', '-y'], options);
  1408. // })
  1409. var g = {
  1410. 'client': () => {
  1411. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  1412. console.info('Creating new ember client named : ' + processedArgs._[2]);
  1413. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1414. stdio: ['pipe', process.stdout, process.stderr],
  1415. inherit: true,
  1416. shell: true,
  1417. cwd: path.dirname(__dirname),
  1418. env: env
  1419. })
  1420. },
  1421. 'modelr': () => {
  1422. var tasks = [
  1423. () => {
  1424. var p = nodeShellExec('"ember"', [
  1425. 'g'
  1426. , 'modelr'
  1427. , processedArgs._[2]], {
  1428. inherit: true, shell: true, env: process.env
  1429. }).then(() => {
  1430. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  1431. return true;
  1432. }).catch((e) => { console.error(e) })
  1433. return p;
  1434. },
  1435. () => {
  1436. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1437. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  1438. chromeprefs = JSON.parse(chromeprefs)
  1439. var previous = chromeprefs.download.default_directory;
  1440. var parentDir = path.dirname(__dirname);
  1441. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1442. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1443. // PB : TODO -- detect where chrome is installed.
  1444. // PB : TODO -- set the download dir to the place where files are needed.
  1445. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1446. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1447. , '--profile-directory="chess"'
  1448. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1449. inherit: true, shell: true
  1450. , env: process.env
  1451. }).then(() => {
  1452. chromeprefs.download.default_directory = previous;
  1453. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1454. return true;
  1455. }).catch((e) => { console.error(e) })
  1456. return p;
  1457. }
  1458. ,
  1459. () => {
  1460. console.log('Browser process should have closed here....')
  1461. return true;
  1462. }
  1463. ]
  1464. any(tasks)
  1465. }
  1466. }
  1467. g[processedArgs._[1]]();
  1468. }
  1469. }
  1470. var util = require('util');
  1471. var cliname = 'elxr';
  1472. var ver = '1.1';
  1473. var readme = `
  1474. Command syntax examples
  1475. elxr
  1476. Displays help. Same as elxr h
  1477. elxr i
  1478. Runs interactive propmts to help choose installation options.
  1479. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  1480. General command syntax.
  1481. Eg: NODE_ENV=development elxr pull elixir
  1482. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  1483. The specific cmd defines what the value is interpreted as.
  1484. There are several cmds that do not require an {{instancename}} parameter.
  1485. Eg: elxr remote remove origin
  1486. Git operations or passthrough external commands on all repository folders in you working directory.
  1487. Main objectives.
  1488. elxr cli is a wrapper around other shell commands and api based operations.
  1489. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  1490. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  1491. `;
  1492. var help = `
  1493. ${readme}
  1494. # list of commands... please refer dveloper documentation for ${cliname}
  1495. ${
  1496. // util.inspect(
  1497. [Object.keys(op)]
  1498. // )
  1499. }
  1500. `;
  1501. var elxr = {
  1502. help() {
  1503. return chalk.cyanBright(`
  1504. -------------------------------------------------------------------------------
  1505. *** BBH Elixir ***
  1506. -------------------------------------------------------------------------------
  1507. elxr ${ver}
  1508. A cli tool for chess
  1509. ${help}
  1510. -------------------------------------------------------------------------------
  1511. `)
  1512. }
  1513. , info() {
  1514. return chalk.cyanBright(`
  1515. -------------------------------------------------------------------------------
  1516. *** BBH Elixir ***
  1517. -------------------------------------------------------------------------------
  1518. elxr ${ver}
  1519. A cli tool for chess
  1520. -------------------------------------------------------------------------------
  1521. `)
  1522. }
  1523. , getpulltask(def){
  1524. // def can be an instance config
  1525. // Or an object with many repos and elevated repos
  1526. // Or a single repo ( Either Elevated or normal. )
  1527. def = def || {
  1528. repos : selectedinstance.repos,
  1529. elevated : selectedinstance.elevated
  1530. }
  1531. var elevatedpulltasks = null;
  1532. if(def.repo) {
  1533. // Single repo case.
  1534. if(def.repo.requiresElevation) {
  1535. elevatedpulltasks = function() {
  1536. return performPull(def.repo).then(() => {
  1537. return true;
  1538. }).catch((e) => {
  1539. console.error(e)
  1540. })
  1541. }
  1542. return
  1543. }
  1544. else {
  1545. var regularpulltasks = function(){
  1546. var pendingpulls = [];
  1547. pendingpulls.push(performPull(def.repo))
  1548. return Promise.all(pendingpulls).finally(Traq.finally)
  1549. }
  1550. }
  1551. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1552. else return getTaskWithoutElevation({ regularpulltasks})
  1553. }
  1554. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  1555. console.dir(def)
  1556. var env = Object.assign({}, process.env); // Shallow clone it.
  1557. console.log('Running exlr pull : ' + path.dirname(__dirname))
  1558. var useGitPull = processedArgs.useGitPull || false;
  1559. if(def.elevated || def.repos) {
  1560. if(def.elevated) def.requiresElevation = true;
  1561. else delete def.requiresElevation;
  1562. }
  1563. else {
  1564. if(def.requiresElevation) def.elevated = [def]
  1565. else def.repos = [def]
  1566. }
  1567. var regularpulltasks = function(){ return Promise.resolve(true) }
  1568. if(def.elevated){
  1569. elevatedpulltasks = function() {
  1570. return any(def.elevated.map((def) => performPull(def.repo))).then(() => {
  1571. return true;
  1572. }).catch((e) => {
  1573. console.error(e)
  1574. })
  1575. }
  1576. }
  1577. if(def.repos) {
  1578. var regularpulltasks = function(){
  1579. var pendingpulls = [];
  1580. def.repos.forEach((def) => { pendingpulls.push(performPull(def.repo)) })
  1581. return Promise.all(pendingpulls).finally(Traq.finally)
  1582. }
  1583. }
  1584. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1585. else return getTaskWithoutElevation({ regularpulltasks})
  1586. }
  1587. }
  1588. function preworkerconfig(){
  1589. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  1590. gitRepos = selectedinstance.repos
  1591. // gitRepos = ['chess-server-lib'];
  1592. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  1593. elevatedRunasRepos = selectedinstance.elevated
  1594. // Repos that should excluded from merge for releases...
  1595. exludeMergeRepos = selectedinstance.exludeMergeRepos
  1596. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  1597. // mysql -u root -p db_name < drop_all_tables.sql
  1598. var mysql = '../xampp/mysql/bin/mysql'
  1599. var mysqldump = '../xampp/mysql/bin/mysqldump'
  1600. }
  1601. // The main elxr cli process
  1602. function elxrworker() {
  1603. var subcommandlabels = {
  1604. remote : (`remote ${processedArgs._[1] || ''}`).trim()
  1605. }
  1606. var __runcmd = function (label) {
  1607. var distinquishedlabel = subcommandlabels[label] || label
  1608. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  1609. }
  1610. // --runas
  1611. if (processedArgs.runas) {
  1612. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  1613. return __runcmd('runas')
  1614. }
  1615. else return __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  1616. }
  1617. function acquireChoices(selectedinstance) {
  1618. var hasconfig = false;
  1619. console.warn(chalk.yellow(`
  1620. -------------------------------------------------------------------------------
  1621. Warning : Cannot locate your preferred configuration since it was not specified
  1622. You should fork the default chess configuration to customize and make it
  1623. your own instance with a named config as
  1624. {{yourowninstancename}}-config-{{yourchosenenvironment}}
  1625. And then run this tool as follows
  1626. NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  1627. OR
  1628. Run this tool with the following command to use a quick start default.
  1629. elxr --default
  1630. OR
  1631. Choose one of the options below to run interactively.
  1632. We will run your choice at the next prompt.
  1633. -------------------------------------------------------------------------------
  1634. `))
  1635. var prompt = cli.prompter;
  1636. return prompt.ask(`Choose an option :
  1637. d) Install the default chess instance.
  1638. => elxr i chess node_env=development --default
  1639. n) Create your custom new instance interactively
  1640. => elxr i {{instanceName}} node_env={{environment}}
  1641. i) Choose an instance and environment to install
  1642. => elxr i {{instanceName}} node_env={{environment}}
  1643. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  1644. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  1645. h) Help
  1646. q) Quit
  1647. Default <= d
  1648. : `).then((choice) => {
  1649. if (choice && choice === 'd' || !choice) {
  1650. processedArgs._[0] = 'i'
  1651. selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  1652. selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  1653. selectedinstance.reposerver = 'https://git.bbh.org.in'
  1654. }
  1655. else if (choice === 'h') {
  1656. processedArgs._[0] = 'h'
  1657. fs.writeFileSync('run.done', 'noop help');
  1658. console.log(elxr.help()); process.exit()
  1659. }
  1660. else if (choice === 'n' || choice === 'i') {
  1661. var p1 = cli.prompter;
  1662. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1663. processedArgs._[0] = 'i'
  1664. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  1665. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1666. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1667. if (choice === 'n') {
  1668. selectedinstance.reposerver = 'https://git.bbh.org.in'
  1669. console.warn(
  1670. chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  1671. process.exit();
  1672. }
  1673. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1674. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1675. })
  1676. })
  1677. })
  1678. } else if (choice === 'c') {
  1679. var p1 = cli.prompter;
  1680. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1681. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  1682. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1683. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1684. return p1.ask(`Enter cmd :
  1685. p) pull
  1686. Default <= p
  1687. : `).then(function (cmd) {
  1688. if (!cmd || cmd === 'p') {
  1689. processedArgs._[0] = 'pull'
  1690. }
  1691. else processedArgs._[0] = cmd
  1692. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1693. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1694. })
  1695. })
  1696. })
  1697. })
  1698. } else {
  1699. 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.`));
  1700. fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  1701. fs.writeFileSync('run.done', 'noop quit');
  1702. process.exit()
  1703. }
  1704. })
  1705. }
  1706. var mergeObjByKey = function(arrOfObjs, keyName) {
  1707. var keyedDistinct = {}
  1708. var distinctArrOfObjs = []
  1709. arrOfObjs.forEach( o => {
  1710. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o)
  1711. })
  1712. Object.keys(keyedDistinct).forEach(key => {
  1713. distinctArrOfObjs.push( utils.assign( ...keyedDistinct[key] ) ) // PB : TODO -- Shallow use utils.assign
  1714. })
  1715. return distinctArrOfObjs;
  1716. }
  1717. var cacheWriteInstanceConfig = function(chessinstances){
  1718. var instanceName = chessinstances['current_run'].instanceName;
  1719. var node_env = chessinstances['current_run'].node_env;
  1720. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos, 'repo') ;
  1721. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated, 'repo') ;
  1722. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  1723. }
  1724. var acquireConfig = function (selected) {
  1725. var configrepo = selected.instanceName + '-config-' + selected.node_env;
  1726. return performPull(configrepo).then(() => {
  1727. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  1728. selectedinstance = require(manifestpath)()
  1729. // Config from server always override merges into selection ecept for the current selection.
  1730. // PB : TODO -- utils.assign Array merges are non-distinct...
  1731. if(!selectedinstance.repos[0].repo) {
  1732. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  1733. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  1734. }
  1735. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  1736. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  1737. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  1738. }
  1739. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = utils.assign(selected, selectedinstance)
  1740. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  1741. cacheWriteInstanceConfig(chessinstances)
  1742. ENV.NODE_ENV = selectedinstance.node_env;
  1743. })
  1744. .catch((e) => {
  1745. console.error(e)
  1746. console.error('Config acquisition failed.')
  1747. })
  1748. }
  1749. var launchpath = process.cwd().replace(/\\/, '/')
  1750. var thisscriptdir = __dirname
  1751. var instanceroot = launchpath;
  1752. var detectInstance = function () {
  1753. console.log(`launchpath = ${launchpath}`)
  1754. console.log(`thisscriptdir = ${thisscriptdir}`)
  1755. var root = launchpath;
  1756. // We need a reference to the root director for elxr cli to be properly oriented.
  1757. if ((launchpath + path.normalize('/elxr')) === thisscriptdir) {
  1758. // We ran unbuilt from the proper root with elxr subfolder.
  1759. console.log(`Instance Path : ${root}`)
  1760. }
  1761. else {
  1762. if (launchpath === thisscriptdir) {
  1763. // Same directory doesn't mean we are being run from elxr directory or the root directory.
  1764. // It could be a standalone elxr build which may or maynot be in the proper location.
  1765. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  1766. // Unbuilt therefore we are in the elxr directory.
  1767. root = path.normalize(launchpath + '/..');
  1768. }
  1769. else {
  1770. // Built version.
  1771. // check if we have a elxr subfolder.
  1772. if (fs.existsSync(launchpath + '/..' + path.normalize('/elxr'))) {
  1773. // Probably in the right place.
  1774. root = path.normalize(launchpath + '/..');
  1775. }
  1776. else {
  1777. // Assume launchpath is meaningless.
  1778. // Figure it out from the input instance name and environment parameters if we are in the right location.
  1779. root = path.normalize(launchpath + '/' + processedArgs._[1] + '/' + processedArgs.node_env)
  1780. }
  1781. }
  1782. }
  1783. }
  1784. instanceroot = root.replace(/\\/, '/');
  1785. __default.root = root;
  1786. return Promise.resolve(__default);
  1787. }
  1788. //
  1789. var __default = {
  1790. // Default is public server only.
  1791. // All public repos are by default available.
  1792. reposervers: ['https://git.bbh.org.in']
  1793. , repos: [
  1794. 'setup'
  1795. , 'elxr'
  1796. , 'loopback-connector-mysql'
  1797. , 'loopback-jsonapi-model-serializer'
  1798. , 'loopback-component-jsonapi'
  1799. , 'ember-service-worker'
  1800. , 'ember-service-worker-asset-cache'
  1801. , 'ember-service-worker-cache-fallback'
  1802. , 'ember-service-worker-index'
  1803. , 'ember-sw-client-route'
  1804. ]
  1805. , elevated: []
  1806. , exludeMergeRepos: {}
  1807. , instanceName: 'chess'
  1808. // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
  1809. , node_env: 'development'
  1810. }
  1811. var __interactve_promts = {
  1812. get reposerver(){
  1813. return cli.prompt(this.reposervers, 'git default repo').then(reposerver => {
  1814. Object.defineProperty(this, 'reposerver', {
  1815. value: reposerver,
  1816. writable: false,
  1817. configurable : true,
  1818. enumerable : true
  1819. });
  1820. return reposerver
  1821. })
  1822. }
  1823. , set reposerver(reposerver){
  1824. Object.defineProperty(this, 'reposerver', {
  1825. value: reposerver,
  1826. writable: false,
  1827. configurable : true,
  1828. enumerable : true
  1829. });
  1830. return reposerver
  1831. }
  1832. }
  1833. var downloadsdir = '../Downloads';
  1834. var prerequisites = [
  1835. {
  1836. shellcmd: 'git',
  1837. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  1838. , installer: 'Git-2.31.0-64-bit.exe'
  1839. , installcmd: ['cmd', ['/c', 'start',
  1840. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  1841. , '/VERYSILENT'
  1842. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  1843. ]]
  1844. , preinstallsteps: function() {
  1845. var prompt = cli.prompter;
  1846. var steps = [
  1847. () => {
  1848. if (!existsSync(downloadsdir + '/' + this.installer)) {
  1849. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  1850. }
  1851. else return Promise.resolve(true)
  1852. }
  1853. ]
  1854. var prompts = [
  1855. () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
  1856. , () => prompt.ask(`git email : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
  1857. ]
  1858. return any([any(steps), any(prompts)])
  1859. }
  1860. , installsteps: function () {
  1861. return any([this.installcmd].map(callsheltask))
  1862. }
  1863. , postinstallsteps: function(){
  1864. var prompt = cli.prompter;
  1865. var gitUser = 'guest';
  1866. var gitEmail = 'guest@bbh.org.in';
  1867. var prompts = [];
  1868. prompts.push(
  1869. ()=>{
  1870. var choices = { 0 : 'guest', 1 : 'chessdemo' }
  1871. return cli.prompt(choices, 'git user name').then(gituser => gitUser = gituser)
  1872. }
  1873. )
  1874. prompts.push(
  1875. ()=>{
  1876. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  1877. return cli.prompt(choices, 'git user email').then(gitemail => gitEmail = gitemail)
  1878. }
  1879. )
  1880. return any(prompts).then(()=>{
  1881. var steps = [
  1882. ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  1883. , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  1884. ]
  1885. return any(steps.map(callsheltask)).then(() => {
  1886. })
  1887. });
  1888. }
  1889. , install: function () {
  1890. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  1891. }
  1892. , verifyAndInstall : function(){
  1893. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  1894. if(exists) {
  1895. // return any(['git', ['config', '--global', '-l']].map(callsheltask))
  1896. return this.getUser(null, this.postinstallsteps.bind(this))
  1897. }
  1898. return this.install();
  1899. });
  1900. }
  1901. , getUser : function(repo, onNoResult){
  1902. onNoResult = onNoResult || function(){return false}
  1903. var globalOrLocal = '--global';
  1904. if(!repo) globalOrLocal = '--global';
  1905. else globalOrLocal = '--local'
  1906. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(callsheltask)).then((result)=>{
  1907. // not yet configured.
  1908. if(!result.success) return onNoResult()
  1909. else {
  1910. var users = result.messages[0].trim().split('\n');
  1911. if(users.length === 0 ||
  1912. users.length === 1 && users[0] === 'guest') {
  1913. return onNoResult()
  1914. }
  1915. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  1916. }
  1917. })
  1918. .catch((e)=>{
  1919. console.log(e)
  1920. return onNoResult()
  1921. })
  1922. }
  1923. }
  1924. ,
  1925. {
  1926. shellcmd: 'node',
  1927. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  1928. , installer: 'node-v14.16.0-x64.msi'
  1929. , installcmd: ['MSIEXEC.exe', ['/i'
  1930. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  1931. , 'ACCEPT=YES', '/passive']]
  1932. , install : function() { return any([this.installcmd].map(callsheltask)).then(() => { }) }
  1933. }
  1934. ]
  1935. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  1936. function ensureDirectoryExistence(filePath) {
  1937. var dirname = path.dirname(filePath);
  1938. if (fs.existsSync(dirname)) {
  1939. return filePath;
  1940. }
  1941. ensureDirectoryExistence(dirname);
  1942. fs.mkdirSync(dirname);
  1943. return filePath;
  1944. }
  1945. var mainTasks = [];
  1946. function verifyAndInstallPrerequisites() {
  1947. fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
  1948. // PB : TODO include and build from files... using rollup..
  1949. var downloadbatch =
  1950. `::**************************************************************************
  1951. :Download_ <url> <File>
  1952. Powershell.exe ^
  1953. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  1954. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  1955. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  1956. exit /b
  1957. ::**************************************************************************`
  1958. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch)
  1959. var windowselevate =
  1960. `
  1961. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  1962. <script language="vbscript">
  1963. document.title = "elxr control panel"
  1964. self.ResizeTo 200,600
  1965. Sub Window_Onload
  1966. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  1967. End Sub
  1968. Set objShell = CreateObject("WScript.Shell")
  1969. Set objENV = objShell.Environment("Process")
  1970. dim NODE_ENV
  1971. NODE_ENV = objENV("NODE_ENV")
  1972. </script>
  1973. <script language="javascript">
  1974. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  1975. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  1976. // alert(windowselevate.commandLine)
  1977. var args = windowselevate.commandLine.split('"').slice(3);
  1978. // alert(args)
  1979. var processedArgs = { _ : [] }
  1980. var namedArgs = [];
  1981. for(var item in args){
  1982. if(args[item].charAt(0) === '-'){
  1983. namedArgs.push(args[item])
  1984. var split = args[item].split('=');
  1985. processedArgs[split[0].slice(2)] = split[1] || true;
  1986. }
  1987. else processedArgs._.push(args[item]);
  1988. }
  1989. // args = args.forEach(function(item){ })
  1990. // alert('processedArgs._ : ' + processedArgs._);
  1991. // alert(processedArgs.runas);
  1992. // PB : TODO -- Convert all the cli args back to string.
  1993. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  1994. // alert(cargs)
  1995. var shell = new ActiveXObject('shell.application');
  1996. // alert('launching node privilged. ' + processedArgs['nodepath'])
  1997. // shell.ShellExecute('where', 'node', '', '', 10);
  1998. shell.ShellExecute('node', cargs, '', 'runas', 1);
  1999. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  2000. var fso = new ActiveXObject('Scripting.FileSystemObject');
  2001. window.onload = function() {
  2002. document.body.style.backgroundColor = 'black';
  2003. document.body.style.fontFamily = 'arial';
  2004. var log = document.createElement('div');
  2005. log.innerHTML='Please Wait';
  2006. function l(msg){ log.innerHTML+= msg; };
  2007. log.style.color = 'blue';
  2008. log.style.width = '95%';
  2009. log.id = 'log';
  2010. document.body.appendChild(log);
  2011. l('<Br/>Current config : ')
  2012. l('<Br/>NODE_ENV = ' + NODE_ENV)
  2013. l('<Br/>cmd = ' + processedArgs._[0])
  2014. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  2015. l('<Br/><Br/>')
  2016. var timer = function(){
  2017. l('.');
  2018. if(fso.FileExists("run.done")) close();
  2019. else window.setTimeout(timer, 1000);
  2020. };
  2021. window.setTimeout(timer, 3000);
  2022. };
  2023. </script>
  2024. </html>
  2025. `
  2026. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate)
  2027. var downloadtasks = [];
  2028. var installtasks = [];
  2029. prerequisites.forEach(preq => {
  2030. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  2031. if (exists) console.log(`${preq.shellcmd} exists`)
  2032. else {
  2033. console.log(`${preq.shellcmd} is not installed`)
  2034. return preq.preinstallsteps.call(preq).then(() => {
  2035. installtasks.push(preq.install.bind(preq))
  2036. })
  2037. }
  2038. }))
  2039. })
  2040. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  2041. }
  2042. var getPromptableAsyncPropDescriptor = function(propName, choices, defaultchoise){
  2043. return {
  2044. get (){
  2045. return cli.prompt( choices, propName, defaultchoise).then(propValue => {
  2046. Object.defineProperty(this, propName, {
  2047. value: propValue,
  2048. writable: false,
  2049. configurable : true,
  2050. enumerable : true
  2051. });
  2052. return propValue
  2053. })
  2054. }
  2055. // , set (propValue){
  2056. // Object.defineProperty(this, propName, {
  2057. // value: propValue,
  2058. // writable: false,
  2059. // configurable : true,
  2060. // enumerable : true
  2061. // })
  2062. // return propValue;
  2063. // }
  2064. , configurable : true
  2065. , enumerable : true
  2066. }
  2067. }
  2068. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  2069. var selectedinstance = null;
  2070. var chessinstances = { current_run : {} };
  2071. acquireElevationState().then(() => {
  2072. var skipprerequisites = false;
  2073. var clioverrides = { }
  2074. function initinstances(selected) {
  2075. // PB : TODO -- processedArgs should already be part of selected.
  2076. var instanceName = processedArgs._[1] = processedArgs._[1] || chessinstances.current_run.instanceName || selected.instanceName;
  2077. var node_env = processedArgs.node_env = processedArgs.node_env || chessinstances.current_run.node_env || selected.node_env;
  2078. chessinstances['current_run'] = chessinstances[instanceName][selected.node_env] ?
  2079. { instanceName: instanceName, node_env: node_env } : chessinstances['current_run']
  2080. // chessinstances[chessinstances.current_run.instanceName] = chessinstances[chessinstances.current_run.instanceName] || {}
  2081. if(path.normalize(selected.root) !== path.normalize(chessinstances[instanceName][node_env].root)) {
  2082. throw "Mismatched chessinstances config found " + chessinstances[instanceName][node_env].root + ' does not match ' + selected.root
  2083. }
  2084. // Override sequence.
  2085. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  2086. selectedinstance = Object.assign(
  2087. selected
  2088. , chessinstances[instanceName][node_env]
  2089. , clioverrides
  2090. // , __interactve_promts -- Cant just override. Also need selectedinstance to be ready...
  2091. );
  2092. chessinstances[instanceName] = chessinstances[instanceName] || {}
  2093. chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  2094. if(!selectedinstance.repos[0].repo) {
  2095. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  2096. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  2097. }
  2098. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  2099. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  2100. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  2101. }
  2102. // Config from server always override merges into selection except for the current selection.
  2103. // PB : TODO -- utils.assign Array merges are non-distinct...
  2104. chessinstances[instanceName][node_env] = selectedinstance = utils.assign(selected, selectedinstance)
  2105. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  2106. cacheWriteInstanceConfig(chessinstances)
  2107. // PB : TODO -- We should probably write the new server config also...
  2108. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  2109. return chessinstances
  2110. }
  2111. function acquirelocalinstances(selected){
  2112. var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
  2113. return chessinstances
  2114. }
  2115. var noprerequisites = {
  2116. add : true, 'set-url' : true, 'repo-relocate' : true
  2117. , remote : true
  2118. }
  2119. var skipprereqs = {}
  2120. var maintask = () => {
  2121. // Default cmd to run !
  2122. processedArgs._[0] === processedArgs._[0] || 'pull';
  2123. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  2124. if(!noprerequisites[processedArgs._[0]]
  2125. && !skipprereqs[processedArgs._[0]]
  2126. ) {
  2127. return prerequisites.git.verifyAndInstall().then(()=>{
  2128. var e = { message : 'verifyAndInstall', success : true}
  2129. return acquireConfig(selectedinstance).catch((err) => {
  2130. e = err;
  2131. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  2132. console.error(err)
  2133. }).then(() => { preworkerconfig(); return elxrworker(true) })
  2134. // .finally(()=>{
  2135. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  2136. // if(!e.success) fs.writeFileSync('run.done', 'error');
  2137. // // return process.exit()
  2138. // })
  2139. })
  2140. }
  2141. else {
  2142. console.log('cmd has no preqs or has been configured to skip preqs')
  2143. preworkerconfig()
  2144. return elxrworker()
  2145. }
  2146. }
  2147. const retaincount = 2
  2148. var min = runtimestamp;
  2149. var collect = []
  2150. if(noprerequisites[processedArgs._[0]]
  2151. || skipprereqs[processedArgs._[0]]
  2152. ) {
  2153. return elxrworker()
  2154. }
  2155. return detectInstance().then((detectedInstance)=>{
  2156. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  2157. processedArgs.node_env ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env
  2158. : (process.env.NODE_ENV && process.env.NODE_ENV.trim()) ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()): null;
  2159. clioverrides.reconfirm = processedArgs.reconfirm
  2160. selectedinstance = Object.assign(detectedInstance, clioverrides);
  2161. var todo = Promise.resolve(true);
  2162. var promptkeys = { 'instanceName' : processedArgs._[1] }
  2163. if(clioverrides.reconfirm) {
  2164. var reconfirm = {
  2165. 'instanceName' : selectedinstance['instanceName'] === 'chess'
  2166. }
  2167. }
  2168. else {
  2169. var reconfirm = {};
  2170. }
  2171. var prompts = [];
  2172. var eachPrompt = function(k, i, a){
  2173. // No local instances config found. We use a default initialized instance available in selectedinstance
  2174. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  2175. if(promptkeys[k] && selectedinstance[k] !== promptkeys[k] || promptkeys[k] === undefined && selectedinstance[k] === undefined
  2176. || reconfirm[k]) {
  2177. prompts.push(async ()=>{
  2178. // PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
  2179. // We take a snapshot... Shallow.. !! If required deep should be used based on use case.
  2180. // If latest altered state is required we can reerence this directly.
  2181. // var asyncthis = Object.assign(this);
  2182. Object.defineProperty(selectedinstance, k, getPromptableAsyncPropDescriptor(k, choices[k], promptkeys[k] || selectedinstance[k] ));
  2183. return await selectedinstance[k]
  2184. })
  2185. }
  2186. delete promptkeys[k]
  2187. }
  2188. try {
  2189. chessinstances = acquirelocalinstances(selectedinstance);
  2190. initinstances(selectedinstance)
  2191. var instanceNameChoices = new Set(Object.keys( chessinstances) )
  2192. instanceNameChoices.delete('current_run')
  2193. instanceNameChoices.add(selectedinstance['instanceName'])
  2194. if(promptkeys['instanceName']) instanceNameChoices.add(promptkeys['instanceName'])
  2195. var choices = {
  2196. 'instanceName' : Array.from(instanceNameChoices)
  2197. , 'reposerver' : selectedinstance['reposervers']
  2198. }
  2199. Object.keys(__interactve_promts).forEach(eachPrompt, __interactve_promts)
  2200. Object.keys(promptkeys).forEach(eachPrompt, promptkeys)
  2201. todo = any(prompts).then(()=>{ return selectedinstance })
  2202. }
  2203. catch (e) {
  2204. console.error(e) // Missing chessinstances is not an error...
  2205. initinstances(selectedinstance)
  2206. var instanceNameChoices = new Set(Object.keys( chessinstances) )
  2207. instanceNameChoices.delete('current_run')
  2208. instanceNameChoices.add(selectedinstance['instanceName'])
  2209. if(promptkeys['instanceName']) instanceNameChoices.add(promptkeys['instanceName'])
  2210. var choices = {
  2211. 'instanceName' : Array.from(instanceNameChoices)
  2212. , 'reposerver' : selectedinstance['reposervers']
  2213. }
  2214. Object.keys(__interactve_promts).forEach(eachPrompt, __interactve_promts)
  2215. Object.keys(promptkeys).forEach(eachPrompt, promptkeys)
  2216. todo = any(prompts).then(()=>{ return selectedinstance })
  2217. if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  2218. // Weve been told what to do.
  2219. todo = todo.then(() => { return acquireChoices(selectedinstance) })
  2220. }
  2221. todo = todo.then(() => {
  2222. try {
  2223. chessinstances = acquirelocalinstances(selectedinstance)
  2224. initinstances(selectedinstance)
  2225. }
  2226. catch (e) {
  2227. console.error(e)
  2228. console.log('No local instances config found in current root = ' + selectedinstance.root);
  2229. console.log('A config will be createed with the instance and environment chosen...')
  2230. // return (async ()=>{return await __default.reposerver})().then(()=>{
  2231. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  2232. // return selectedinstance = Object.assign(__default, selectedinstance);
  2233. // })
  2234. return selectedinstance
  2235. }
  2236. })
  2237. }
  2238. return todo
  2239. })
  2240. .then(()=>{
  2241. if(!__isElevated) {
  2242. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/readme.txt`)
  2243. // collect garbage
  2244. return dirs( (dir)=>{
  2245. var matches = /run-(.*)/gm.exec(dir.name)
  2246. if(matches) {
  2247. if(+(matches[1]) < min) {
  2248. min = matches[1]
  2249. collect.splice( 0, 0, matches[1] )
  2250. }
  2251. else collect.push(matches[1])
  2252. }
  2253. }, `${selectedinstance.root}/.elxr` ).then(()=>{
  2254. // delete garbage
  2255. if(collect.length > retaincount) {
  2256. var asyncs = [];
  2257. while((collect.length - asyncs.length) > retaincount) {
  2258. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  2259. }
  2260. return Promise.all(asyncs)
  2261. }
  2262. else return true
  2263. })
  2264. }
  2265. else return true;
  2266. })
  2267. .then(()=>{
  2268. // PB : TODO -- Keep only the last n runs...
  2269. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  2270. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
  2271. if (!skipprerequisites && !__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
  2272. mainTasks.push(maintask)
  2273. return any(mainTasks);
  2274. })
  2275. })
  2276. // detect if alread installed -> Take no action.
  2277. // download if no installer avalable -> next()
  2278. // install
  2279. function chackandinstall(items) {
  2280. var tasks = []
  2281. items.forEach(item => {
  2282. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  2283. })
  2284. return Promise.all(tasks).then(existances => {
  2285. existances.forEach((exists, i) => {
  2286. if (!exists) {
  2287. return downloadandinstall([items[i]])
  2288. }
  2289. })
  2290. })
  2291. }
  2292. function downloadandinstall(items) {
  2293. var tasks = []
  2294. items.forEach(item => {
  2295. tasks.push(getTaskDownload(item))
  2296. })
  2297. return Promise.all(tasks)
  2298. }
  2299. // Sample instances config.
  2300. // var instances = {
  2301. // "elixir": {
  2302. // "production": {
  2303. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  2304. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  2305. // , "exludeMergeRepos": {
  2306. // "elixir-config-development": true, "elixir-config-test": true
  2307. // , "elixir-config-production": true, "elixir-data": true
  2308. // }
  2309. // , "instanceName": "elixir", "node_env": "production"
  2310. // }
  2311. // },
  2312. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  2313. // }
  2314. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...