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

index.js 94KB

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