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

index.js 96KB

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