Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

index.js 133KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506
  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 __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b'
  12. const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  13. const runtimestamp = (new Date()).getTime();
  14. function getVersion() { return BUILD_VERSION; }
  15. console.log(getVersion());
  16. // 'use strict';
  17. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  18. // PB : TODO --
  19. // runas bypass non elevated tasks when we request privelege
  20. // runas message is always error needs to be fixed.
  21. // runas wait needs to be parallelized.
  22. // suppress elevation check error messages
  23. // support runas lauched directly from shell.
  24. // pass in environment in hta to shellexecute.
  25. // PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
  26. (function () {
  27. "use strict";
  28. if (!Array.prototype.earlyreduce) {
  29. Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
  30. var iterable = this;
  31. var donecallback = donecallback || (a=>a)
  32. var result = { value : initialValue === undefined ? iterable[0] : initialValue };
  33. initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
  34. // function *earlyReduceGenerator(acc, v, i, a) {
  35. for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
  36. var element = iterable[i]
  37. result = eachcallback(result, element, i, iterable)
  38. if(result.done) return donecallback(result)
  39. }
  40. // }
  41. return donecallback(result)
  42. }
  43. }
  44. }());
  45. const { existsSync } = require('fs');
  46. const existsFolderSync = existsSync;
  47. const fs = require('fs')
  48. const cliargs = utils.cliargs;
  49. const processedArgs = cliargs(process.argv.slice(2));
  50. console.dir(processedArgs)
  51. // PB : TODO -- defaults for valuless arguments if passed.
  52. // Object.keys(processedArgs).forEach(a=>{
  53. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  54. // }
  55. // })
  56. var subcommandlabels = {
  57. remote : (`remote ${processedArgs._[1] || ''}`).trim()
  58. }
  59. var interpretrun = function(){
  60. var cmds = {
  61. 'remote' : function() {
  62. return { cmd : subcommandlabels['remote'], runchoice : 'c' }
  63. }
  64. }
  65. var cmd = processedArgs._[0];
  66. var clioverrides = { cmd }
  67. processedArgs.node_env ? clioverrides.node_env = processedArgs.node_env
  68. : (process.env.NODE_ENV && process.env.NODE_ENV.trim())
  69. ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) : null;
  70. return cmds[cmd] ? cmds[cmd]() : (function(){
  71. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  72. return clioverrides
  73. })()
  74. }
  75. var clioverrides = interpretrun()
  76. console.dir(clioverrides)
  77. // Object.keys(clioverrides).forEach( prop => { })
  78. var globSync = require('glob').sync;
  79. var ENV = Object.assign({}, process.env); // Shallow clone it.
  80. const { readdir } = require("fs").promises
  81. // Directory shallow walk and do perform on each dir.
  82. const dirs = async (perform, path) => {
  83. for (const dir of await readdir(path || selectedinstance.root, { withFileTypes: true })) {
  84. if (dir.isDirectory()) perform(dir)
  85. }
  86. }
  87. var getShellTask = (command, args, options) => {
  88. options = options || {}
  89. var callshell = command === 'rm' ? getgitbashtask : getshelltask;
  90. return () => {
  91. var p = callshell( [command, args, Object.assign({
  92. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  93. }, options)
  94. ])()
  95. if (options.ignorefailures) {
  96. return p.catch(e => {
  97. // Ignore. Not a major error.
  98. })
  99. }
  100. else return p;
  101. }
  102. }
  103. var callshelltask = (args) => {
  104. // console.dir(args)
  105. if( Object.prototype.toString.call(args) === '[object Function]' ) {
  106. return args;
  107. }
  108. return getshelltask(args)()
  109. }
  110. var getshelltask = (args) => {
  111. return args[0] === 'rm' ? getgitbashtask(args) : () => { return nodeShellExec.apply(null, args) } }
  112. var getgitbashtask = (args) => { return () => {
  113. return nodeShellExec( `"${gitbash}"`, ['-c', `"${args[0]} ${args[1].join(' ')}"`], args[2]) }
  114. }
  115. var getTaskCheckExists = (command, options) => {
  116. options = options || {}
  117. return () => {
  118. var p = nodeShellExec.apply(null, ['where', [command]])
  119. if (options.ignorefailures) {
  120. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  121. return false;
  122. })
  123. }
  124. else return p.then(() => { return true });
  125. }
  126. }
  127. var getTaskWithElevation = function(tasdef){
  128. return ()=>{
  129. if (__isElevated) {
  130. return tasdef.elevatedpulltasks().then(()=>{
  131. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  132. fs.writeFileSync('run.done', 'success')
  133. }).catch(e=>{
  134. fs.writeFileSync('run.done', 'failure')
  135. });
  136. }
  137. else {
  138. // PB : TODO -- Rename op['runas'] to 'elevate'
  139. var __runasresult = null;
  140. return op['runas']().then((r) => { return __runasresult = r; })
  141. .catch((e) => {
  142. console.error(e)
  143. })
  144. .finally(() => {
  145. if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done')
  146. if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
  147. })
  148. }
  149. }
  150. }
  151. var getTaskWithoutElevation = function(tasdef){
  152. return ()=>{
  153. if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  154. else Promise.resolve(true)
  155. }
  156. }
  157. var gitops = {
  158. getdiscoverbranchcmd : function(repo){
  159. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  160. var cmd = [gitbash
  161. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  162. , { cwd: instanceroot + '/' + repo, title: 'discoverbranch for ' + repo + ' ' + parameters.join(' ') }]
  163. return cmd
  164. }
  165. }
  166. var getPullCmd = (repo, branch) => {
  167. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  168. // console.log(useGitPull)
  169. var pullCmd = []
  170. if(!branch) {
  171. // console.warn('No branch was specified detecting from working client.')
  172. // First check if working client exists.
  173. // if (existsSync(instanceroot + '/' + repo)) {
  174. pullCmd= gitops.getdiscoverbranchcmd(repo)
  175. // }
  176. // else performpull
  177. }
  178. // var pullCmd = [gitInstallDir
  179. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  180. // , { cwd: instanceroot + '/' + repo, title: 'pull all remotes for ' + repo }]
  181. if(branch) {
  182. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  183. var pullCmd = [ gitbash
  184. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  185. , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  186. }
  187. // var pullCmd = ['pullall', [], { cwd : repo }]
  188. if (useGitPull) pullCmd = ['git', ['pull'], {
  189. inherit: true, shell: true,
  190. cwd: instanceroot + '/' + repo
  191. // , env: process.env
  192. , runas: processedArgs.runas
  193. , title: `git pull ${repo}`
  194. }]
  195. return pullCmd
  196. }
  197. var performPull = (repo, branch) => {
  198. // PB : TODO -- Handle no branch passed in case.
  199. // if(!branch) { throw 'No branch specified' }
  200. if (existsSync(instanceroot + '/' + repo)) {
  201. var branchprint = branch ? ' branch :' + branch : '';
  202. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  203. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  204. if (__isElevated) {
  205. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  206. }
  207. else statuslog.statuslog(null, repo)
  208. return true;
  209. })
  210. .catch((e) => {
  211. e.repo = repo;
  212. if (__isElevated) {
  213. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  214. }
  215. else statuslog.statuslog(e); console.error(e)
  216. })
  217. }
  218. else {
  219. console.log('cloning ' + repo)
  220. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  221. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'],
  222. {
  223. inherit: true, shell: true,
  224. env: process.env
  225. , cwd : instanceroot
  226. , runas: processedArgs.runas
  227. }).catch((e) => {
  228. throw e;
  229. }).then(() => {
  230. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  231. {
  232. inherit: true, shell: true,
  233. env: process.env
  234. , cwd: instanceroot + '/' + repo
  235. , runas: processedArgs.runas
  236. , title: `git core.symlinks --replace-all true for ${selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'}`
  237. })
  238. .then(() => {
  239. if (__isElevated) {
  240. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  241. }
  242. else statuslog.statuslog(null, repo)
  243. })
  244. .catch((e) => {
  245. e.repo = repo;
  246. if (__isElevated) {
  247. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  248. }
  249. else statuslog.statuslog(e);
  250. })
  251. })
  252. .catch(e => {
  253. e.repo = repo;
  254. if (__isElevated) {
  255. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  256. }
  257. else statuslog.statuslog(e);
  258. })
  259. }
  260. }
  261. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  262. // -- Currently workaround is to always run from a non-elevated shell.
  263. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  264. var acquireElevationState = () => {
  265. if (__isElevated === null) {
  266. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  267. inherit: true
  268. // , shell: true
  269. , stdio: 'ignore'
  270. , env: process.env
  271. , title: `check privileged execution mode using "fsutil dirty query C:"`
  272. }).then((exitcode) => {
  273. console.log('Elevated')
  274. __isElevated = true;
  275. return true;
  276. }).catch(() => {
  277. __isElevated = false;
  278. console.log('Not Elevated');
  279. return false;
  280. });
  281. }
  282. else return Promise.resolve(__isElevated);
  283. }
  284. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current GITEA username
  285. var defaultRepoOwner = 'chess';
  286. var elevatedRunasRepos = null
  287. var gitRepos = null
  288. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  289. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  290. var dbForLabel = function (label) {
  291. var dbsForLabel = {
  292. devmysql: 'mysql'
  293. , development: 'mssql'
  294. , production: 'mssql'
  295. }
  296. return dbsForLabel[label] || 'mysql'
  297. }
  298. // SAM : TODO Use nodeshellexec where to detect git installation dir
  299. var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe"
  300. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  301. // Relevant git repos
  302. var exludeMergeRepos = [];
  303. var useGitPull = processedArgs.useGitPull || false;
  304. var configPromise = null
  305. // elxr cli operations
  306. var noprerequisites = {
  307. add : true, 'set-url' : true, 'repo-relocate' : true
  308. , remote : true, 'c' : true, 'h' : true
  309. , httpget : true, getuser : true
  310. // , 'undefined' : true
  311. }
  312. var reconfirmcmds = { create : true }
  313. var op = {
  314. 'h': () => { console.log(elxr.help()); return '-h' }
  315. , 'clean' : () => {
  316. // delete all node_module folders and links.
  317. var tasklist = [];
  318. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot )
  319. return Promise.all(tasklist)
  320. }
  321. // , 'undefined': () => { return acquireChoices( {} ); }
  322. , 'reset': () => {
  323. // Reset NPM packages semver so major versions can be updated.
  324. const fs = require('fs')
  325. const wipeDependencies = (__package) => {
  326. const file = fs.readFileSync(__package + '/package.json')
  327. const content = JSON.parse(file)
  328. for (var devDep in content.devDependencies) {
  329. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  330. content.devDependencies[devDep] = '*';
  331. }
  332. }
  333. for (var dep in content.dependencies) {
  334. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  335. content.dependencies[dep] = '*';
  336. }
  337. }
  338. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  339. }
  340. var repos = ['client'];
  341. // repos = gitRepos;
  342. repos.forEach(wipeDependencies)
  343. // if (require.main === module) {
  344. // } else {
  345. // module.exports = wipeDependencies
  346. // }
  347. }
  348. , 'upgrade': () => {
  349. console.log('upgrade.......')
  350. var tasks = [
  351. () => {
  352. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  353. inherit: true, shell: true
  354. , env: process.env
  355. }).catch((e) => { console.error(e) })
  356. p.position = 1;
  357. console.log('One')
  358. return p;
  359. }
  360. , () => {
  361. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  362. inherit: true, shell: true
  363. , env: process.env
  364. }).catch((e) => { console.error(e) })
  365. p.position = 2;
  366. console.log('Two')
  367. return p;
  368. }
  369. , () => {
  370. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  371. inherit: true, shell: true
  372. , env: process.env
  373. }).catch((e) => { console.error(e) })
  374. p.position = 3;
  375. console.log('Three')
  376. return p;
  377. }
  378. , () => {
  379. var p = nodeShellExec('n', ['latest'], {
  380. inherit: true, shell: true
  381. , env: process.env
  382. }).catch((e) => { console.error(e) })
  383. p.position = 4;
  384. console.log('Four')
  385. return p;
  386. }
  387. ]
  388. any(tasks)
  389. console.log('.......done')
  390. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  391. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  392. console.info('Uninstalling existing ember globally');
  393. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  394. stdio: ['pipe', process.stdout, process.stderr],
  395. inherit: true,
  396. shell: true,
  397. cwd: path.dirname(__dirname),
  398. env: env
  399. })
  400. step1.on('close', () => {
  401. console.info('Installing ember globally');
  402. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  403. stdio: ['pipe', process.stdout, process.stderr],
  404. inherit: true,
  405. shell: true,
  406. cwd: path.dirname(__dirname),
  407. env: env
  408. })
  409. step2.on('close', () => {
  410. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  411. stdio: ['pipe', process.stdout, process.stderr],
  412. inherit: true,
  413. shell: true,
  414. cwd: path.dirname(__dirname),
  415. env: env
  416. })
  417. })
  418. })
  419. }
  420. , 'runas': () => {
  421. if(processedArgs.skipelevated) return Promise.resolve({ skipped : true });
  422. console.log('Testing Elevation')
  423. if (__isElevated) {
  424. try {
  425. op[processedArgs.label || processedArgs._[0] || 'undefined']()
  426. }
  427. catch (e) {
  428. console.error('Error Invalid command : ' + e)
  429. fs.writeFileSync('run.done', 'error')
  430. }
  431. finally {
  432. }
  433. }
  434. else {
  435. console.log('Requesting Elevated Privileges');
  436. // Wait for the runas to complete before we read it.
  437. try {
  438. fs.unlinkSync('run.done')
  439. fs.unlinkSync('run.log')
  440. }
  441. catch (e) { } //Ignore
  442. // Find node path to send to hta.
  443. return nodeShellExec('where', ['node']).then(r => {
  444. var namedArgs = [];
  445. console.log('result : ' + JSON.stringify(r))
  446. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; })
  447. // PB : TODO -- Convert all the cli args back to string.
  448. var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  449. // args.push('--nodepath=' + r.messages[r.messages.length - 1])
  450. // if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
  451. // if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
  452. console.dir(processedArgs)
  453. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  454. , {
  455. inherit: true
  456. , shell: true
  457. , env: ENV
  458. , runas: 'self'
  459. , title: `runas`
  460. }
  461. ).then(() => {
  462. // runas returned.
  463. try {
  464. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  465. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  466. runaslog.forEach((logEntry) => {
  467. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry)
  468. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  469. })
  470. }
  471. catch (e) {
  472. // We must have a runas log
  473. statuslog.statuslog(e)
  474. console.error('Run log error probably was not created by runas : ' + e)
  475. }
  476. })
  477. .catch(err => console.error('Elevation failed : ' + err));
  478. })
  479. }
  480. }
  481. , 'push': () => {
  482. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  483. // init remote bare from local
  484. // pushandinitremotebare
  485. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  486. // connect to repo server -- net use 172.16.0.27
  487. // cd 172.16.0.27/repos/
  488. // mkdir repo.git
  489. // cd repo.git
  490. // git init --bare
  491. // cd localrepo
  492. // git remote rename origin githubclone
  493. // git remote add origin //172.16.0.27/repos/repo.git
  494. // git push origin master
  495. var repo = processedArgs._[1];
  496. var sequentialTaskShellCommands = [];
  497. if (!existsSync(`Z:/${repo}.git`)) {
  498. sequentialTaskShellCommands = [
  499. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  500. // inherit : true, shell: true
  501. // , env: process.env
  502. // }]
  503. ['pwd', { cwd: 'Z:', inherit: true }]
  504. , ['mkdir', [`${repo}.git`], {
  505. cwd: `Z:`
  506. , inherit: true, shell: true
  507. , env: process.env
  508. }]
  509. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  510. , ['git', ['init', '--bare'], {
  511. cwd: `Z:/${repo}.git`
  512. , inherit: true, shell: true
  513. , env: process.env
  514. }]
  515. // PB : TODO -- Do this conditionally only...
  516. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  517. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  518. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  519. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  520. // PB : TODO -- If threre is a gitbubclone origin
  521. // Set the master to pull from the local repo.
  522. ]
  523. if (!existsSync(`Z:`)) {
  524. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  525. inherit: true, shell: true
  526. , env: process.env
  527. }])
  528. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  529. // throw 'done'
  530. }
  531. }
  532. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }])
  533. // console.dir(sequentialTaskShellCommands);
  534. var tasks = [];
  535. sequentialTaskShellCommands.forEach(shellcmd => {
  536. // console.log(shellcmd)
  537. tasks.push(() => {
  538. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
  539. return p;
  540. })
  541. })
  542. any(tasks);
  543. }
  544. , 'is-git-repo': (dir) => {
  545. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  546. }
  547. // git remote equivalents...
  548. // git branch --set-upstream-to=elixir-unc/master master
  549. // git push --set-upstream elixir-unc branch..
  550. , 'remote': (args) => {
  551. // Subcommands!
  552. // PB : TODO -- we can now pass in hypehnated args...
  553. if(!processedArgs.v) return false; // Only -v is supported presently..
  554. var serial_perform = (repo) => {
  555. var options = { cwd: instanceroot + '/' + repo }
  556. return [
  557. ['git', ['remote', '-v'], options]
  558. ]
  559. }
  560. var x = (args) => {
  561. var tasq = () => {
  562. // console.log(args)
  563. return nodeShellExec.apply(null, args).catch(e => {
  564. // We continue on failure.
  565. console.error(tasq.toString())
  566. })
  567. }
  568. tasq.toString = function(){
  569. return JSON.stringify(args)
  570. }
  571. return tasq;
  572. }
  573. var perform = (dir) => {
  574. return any(serial_perform(dir.name).map(x))
  575. }
  576. dirs(perform)
  577. }
  578. , 'remote set-url': (args) => {
  579. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  580. var __args = {
  581. remotename : args.remotename || processedArgs._[2]
  582. , url : args.url || processedArgs._[3]
  583. }
  584. // pushable doesn't mean the remote doesn't support being pushed to.
  585. // 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.
  586. // PB : TODO -- change this to enablepushing.
  587. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  588. var pushable = processedArgs.pushable || false;
  589. remotename = __args.remotename
  590. url = __args.url
  591. var serial_perform_git_seturl = (repo) => {
  592. var options = { cwd: instanceroot + '/' + repo }
  593. // console.log(repo)
  594. if (pushable) {
  595. return [
  596. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  597. , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  598. ]
  599. }
  600. else {
  601. return [
  602. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  603. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  604. ]
  605. }
  606. }
  607. var x = (args) => {
  608. var tasq = () => {
  609. // console.log(args)
  610. return nodeShellExec.apply(null, args).catch(e => {
  611. // We continue on failure.
  612. console.error(tasq.toString())
  613. })
  614. }
  615. tasq.toString = function(){
  616. return JSON.stringify(args)
  617. }
  618. return tasq;
  619. }
  620. var perform_git_seturl = (dir) => {
  621. op['is-git-repo'](dir).then((logEntry) => {
  622. return any(serial_perform_git_seturl(dir.name).map(x))
  623. }).catch((e) => {
  624. // console.log('Failed : ' + dir.name)
  625. })
  626. }
  627. dirs(perform_git_seturl)
  628. }
  629. // , 'reset' : ()=>{
  630. // PB : TODO -- Cant have 2 resets !! | There is an npm reset that should be bundled.
  631. // // Reset the whole installation pertaining to this elxr folder.
  632. // }
  633. , 'remote exists': (args) => {
  634. var __args = {
  635. remotename : args.remotename|| processedArgs._[2]
  636. , url : args.url || processedArgs._[3]
  637. , branch : args.branch || processedArgs._[4]
  638. }
  639. var options = args.repo ? { cwd: instanceroot + '/' + args.repo } : {}
  640. // PB : TODO -- We should evaluate a whole list of remotes passed in from args instead of just one.
  641. var commands = [
  642. // git remote -v| while read remote; do "${remote#origin/}" "$remote"; done
  643. // ['git', ['remote', '-v', '| while read remote; do "${remote#origin/}" "$remote"; done'], utils.assign( {
  644. ['git', ['remote', '-v'], utils.assign( {
  645. evaluateResult : function(err, result){
  646. // var found = result.messages.find( (r)=> { return r.includes( __args.remotename ) })
  647. var remotes = []
  648. var found = false;
  649. console.dir(result.messages)
  650. console.log(result + '---------------')
  651. result.messages.forEach( (line)=> {
  652. console.log(line + '$$$$$$$$$$$$$$$$$$$$')
  653. var matches = line.match(/(.*)?\s\s([^\(]*)?\s?\(?([^\)]*)\)?/);
  654. if(matches) {
  655. var remote = {};
  656. remote[matches[1]] = matches[2];
  657. if( (!matches[3].trim() || matches[3].trim() === 'fetch') && matches[1].trim() === remotename.trim()) {
  658. found = true;
  659. result.url = remote[remotename];
  660. }
  661. }
  662. })
  663. console.dir(remotes)
  664. return [
  665. found
  666. , result
  667. ]
  668. }
  669. } , options) ]
  670. , function(prevserialtaskresult) {
  671. console.log('================================')
  672. var url = __args || prevserialtaskresult.url;
  673. console.dir(prevserialtaskresult)
  674. return getshelltask(['git', ['ls-remote', url], utils.assign( {
  675. evaluateResult : function(err, result){
  676. // fatal: unable to access '${__args.url}/': Failed to connect to git.bbh port 80 after 21025 ms: Timed out
  677. // `fatal: repository '${__args.url}/' not found`
  678. var hasfailed = /^fatal: .*/.test(result.messages.join(' '))
  679. return [
  680. !hasfailed, result
  681. ]
  682. }
  683. } , options) ])()
  684. }
  685. ]
  686. var mapped = commands.map(callshelltask) //.map( p => p.catch(e => e)) // Handle errors later.
  687. return any(mapped).then( allresolved =>{
  688. console.dir(allresolved)
  689. !allresolved[0][0] && !allresolved[1][0] ? console.log('was not added as a remote and url is currently inaccessible.')
  690. : allresolved[0][0] && allresolved[1][0] ? console.log('was added as a remote and url is accessible.')
  691. : allresolved[0][0] && !allresolved[1][0] ? console.log('was added as a remote but url is currently inaccessible.')
  692. : console.log('was not added as a remote but url is currently accessible.')
  693. return !allresolved[0][0] && !allresolved[1][0] ? [0, 0]
  694. : allresolved[0][0] && allresolved[1][0] ? [1, 1] // => was added as a remote and url is accessible.
  695. : allresolved[0][0] && !allresolved[1][0] ? [1, 0] // => was added as a remote but url is currently inaccessible.
  696. : [0, 1] // => was not added and remote and url is accessible.
  697. })
  698. }
  699. , 'remote refresh': (args) => {
  700. var __args = {
  701. remotename : args.remotename|| processedArgs._[2]
  702. , url : args.url || processedArgs._[3]
  703. , branch : args.branch || processedArgs._[4]
  704. }
  705. // use the repo manifest to create missing remotes.
  706. function perform_remote_refresh(dir){
  707. var repo = dir.name
  708. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  709. try {
  710. var remotes = require(`${selectedinstance.root}/${dir.name}/repo-manifest.js`)( null, selectedinstance).remotes || [];
  711. }
  712. catch(e){
  713. var remotes = []
  714. }
  715. // console.log(`${dir.name}/repo-manifest.js` + '---------------------------')
  716. // console.dir(remotes)
  717. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  718. console.log('Processing : ' + dir.name)
  719. var branch = __branch
  720. __args.repo = repo
  721. __args.branch = __branch
  722. var promises = []
  723. remotes.forEach(remote =>{
  724. Object.keys(remote).forEach(remotename => {
  725. __args.remotename = remotename
  726. __args.url = remote[remotename]
  727. promises.push( op['remote exists']( __args ).then( exists => {
  728. if(!exists[0]) {
  729. if(!exists[1]) { console.error( `Skipping inaccessible remote url ${__args.url}` ) }
  730. else return op['remote add']( { remotename,
  731. // PB : TODO -- use the most accessible remote instead of the first available.
  732. url : (utils.js.isArray(remote[remotename]) ? remote[remotename][0] : remote[remotename]), branch
  733. } )
  734. }
  735. })
  736. )
  737. })
  738. })
  739. return Promise.all(promises)
  740. })
  741. .catch((e) => { console.log('Processing Error : ' + dir.name); console.error(e); return { error: true, message: repo } })
  742. }
  743. return dirs(perform_remote_refresh)
  744. }
  745. , 'remote add': (args) => {
  746. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  747. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  748. // That explicitly has a remote name prefix.
  749. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  750. // git branch branch_name -u your_new_remote/branch_name -- older versions
  751. // git branch -vv -- Detect which branch are we tracking.
  752. // default upstream should be users own fork.
  753. // Also need alias branches to
  754. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  755. // probably git merge from all remotes... and relevant branches...
  756. // alias pushall='for i in `git remote`; do git push $i; done;'
  757. // alias pullall='for i in `git remote`; do git pull $i; done;'
  758. // args === processedArgs ? args = {} : null;
  759. var __args = {
  760. remotename : args.remotename|| processedArgs._[2]
  761. , url : args.url || processedArgs._[3]
  762. , branch : args.branch || processedArgs._[4]
  763. }
  764. var remotename = __args.remotename
  765. var url = __args.url
  766. var branch = __args.branch
  767. var pushable = processedArgs.pushable || false;
  768. var serial_perform_git_add = (repo) => {
  769. var options = { cwd: instanceroot + '/' + repo }
  770. // console.log(repo)
  771. if (pushable) {
  772. return [
  773. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  774. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  775. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  776. ]
  777. }
  778. else {
  779. return [
  780. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  781. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  782. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  783. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  784. ]
  785. }
  786. }
  787. var x = (args) => {
  788. return () => {
  789. // console.log(args)
  790. return nodeShellExec.apply(null, args)
  791. }
  792. // return Promise.resolve(true)
  793. }
  794. var perform_git_add = (dir) => {
  795. op['is-git-repo'](dir).then((logEntry) => {
  796. // console.log(code)
  797. if (logEntry.success) {
  798. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  799. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  800. })
  801. .catch((e) => {
  802. any(serial_perform_git_add(dir.name).map(x))
  803. })
  804. }
  805. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  806. }).catch((e) => {
  807. console.log('Failed : ' + dir.name)
  808. })
  809. }
  810. const { readdir } = require("fs").promises
  811. dirs(perform_git_add)
  812. }
  813. , 'remote remove': (args) => {
  814. var __args = {
  815. remotename : args.remotename|| processedArgs._[2]
  816. }
  817. var remotename = __args.remotename
  818. var serial_perform_git_remove = (repo) => {
  819. var options = { cwd: instanceroot + '/' + repo }
  820. // console.log(repo)
  821. return [
  822. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  823. ]
  824. }
  825. var x = (args) => {
  826. return () => {
  827. // console.log(args)
  828. return nodeShellExec.apply(null, args)
  829. }
  830. // return Promise.resolve(true)
  831. }
  832. var perform_git_remove = (dir) => {
  833. op['is-git-repo'](dir).then((logEntry) => {
  834. // console.log(code)
  835. if (logEntry.success) {
  836. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  837. any(serial_perform_git_remove(dir.name).map(x))
  838. })
  839. .catch((e) => {
  840. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`)
  841. })
  842. }
  843. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  844. }).catch((e) => {
  845. // console.log('Failed : ' + dir.name)
  846. })
  847. }
  848. const { readdir } = require("fs").promises
  849. dirs(perform_git_remove)
  850. }
  851. , 'init-gitea': (user) => {
  852. user = user || processedArgs._[1]
  853. if (!user) throw 'User name required'
  854. var serial_perform_init_gitea = (repo) => {
  855. var options = { cwd: instanceroot + '/' + repo }
  856. // console.log(repo)
  857. return [
  858. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  859. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  860. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  861. ]
  862. }
  863. var x = (args) => {
  864. return () => {
  865. // console.log(args)
  866. return nodeShellExec.apply(null, args)
  867. }
  868. // return Promise.resolve(true)
  869. }
  870. var perform_init_gitea = (dir) => {
  871. op['is-git-repo'](dir).then((logEntry) => {
  872. // console.log(code)
  873. if (logEntry.success) {
  874. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  875. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  876. })
  877. .catch((e) => {
  878. any(serial_perform_init_gitea(dir.name).map(x))
  879. })
  880. }
  881. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  882. }).catch((e) => {
  883. // console.log('Failed : ' + dir.name)
  884. })
  885. }
  886. const { readdir } = require("fs").promises
  887. dirs(perform_init_gitea)
  888. }
  889. , 'syncmaster': (label) => {
  890. // Usage :
  891. // elxr pull -- Defaults to run config
  892. var env = Object.assign({}, process.env); // Shallow clone it.
  893. // console.dir(env)
  894. console.log('Running exlr pull : ' + path.dirname(__dirname))
  895. if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'))
  896. if (__isElevated) {
  897. return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
  898. fs.writeFileSync('run.done', 'success')
  899. }).catch(() => {
  900. fs.writeFileSync('run.done', 'error')
  901. })
  902. }
  903. else return op['runas']()
  904. }
  905. , 'repo-relocate' : function(args){
  906. // relocate a subfolder in source repo to same subfolder in target repo with history.
  907. var args = args || {
  908. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  909. , folder : processedArgs._[3] || 'server'
  910. , sourcerepo : processedArgs._[2] || 'client'
  911. , targetrepo : processedArgs._[1] || 'elixir-server'
  912. }
  913. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  914. // , stdio: ['pipe', process.stdout, process.stderr]
  915. , inherit: true,
  916. shell: true,
  917. env: process.env
  918. , runas: processedArgs.runas
  919. }
  920. return op['repo-split'](args).then(()=>{
  921. return op['repo-merge'](args).then(()=>{
  922. // cleanup folder from source.
  923. var cmdseq = [
  924. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  925. // commits have to intentional...
  926. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  927. ]
  928. return any(cmdseq.map(getshelltask))
  929. })
  930. }).catch(e=>{console.error(e)})
  931. }
  932. , 'repo-split' : function(args) {
  933. // https://gist.github.com/smdabdoub/17065c348289158277b5
  934. /**
  935. * Eg : folder, remotebase, sourcerepo, targetrepo
  936. * args.folder = 'server'
  937. * args.remotebase = 'https://git.bbh/chess/'
  938. * args.sourcerepo = 'client'
  939. * args.targetrepo = 'elixir-server'
  940. */
  941. var args = args || {
  942. folder : 'server'
  943. , remotebase : 'http://git.bbh/chess/'
  944. , sourcerepo : 'client'
  945. , targetrepo : 'elixir-server'
  946. }
  947. var options = { cwd: `${instanceroot}/relocate`
  948. // , stdio: ['pipe', process.stdout, process.stderr]
  949. , inherit: true,
  950. shell: true,
  951. env: process.env
  952. , runas: processedArgs.runas
  953. }
  954. var cmdseq = [
  955. // create a temporary working dir in current folder where we started execution.
  956. ['mkdir', [ '-p', `${instanceroot}/relocate`]]
  957. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  958. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  959. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  960. ]
  961. return any(cmdseq.map(getshelltask)).then(() => {
  962. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  963. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  964. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  965. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  966. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  967. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  968. // subtree split and filter-branch are options. We currently use repo-filter.
  969. return op['filter-repo'](args)
  970. }).catch(e=>{console.error(e); throw 'failed'})
  971. }
  972. , 'repo-merge' : function(args) {
  973. // Merge source repo into target repo
  974. var args = args || {
  975. folder : 'server'
  976. , remotebase : 'http://git.bbh/chess/'
  977. , sourcerepo : 'client'
  978. , targetrepo : 'elixir-server'
  979. }
  980. var sourcerepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  981. // , stdio: ['pipe', process.stdout, process.stderr]
  982. , inherit: true,
  983. shell: true,
  984. env: process.env
  985. , runas: processedArgs.runas
  986. }
  987. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  988. // , stdio: ['pipe', process.stdout, process.stderr]
  989. , inherit: true,
  990. shell: true,
  991. env: process.env
  992. , runas: processedArgs.runas
  993. }
  994. var cmdseq = [
  995. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  996. , targetrepooptions ]
  997. // , ['git', ['push', targetrepooptions ] // manual push for now..
  998. ]
  999. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e)})
  1000. }
  1001. , 'filter-repo' : function(args){
  1002. // Merge source repo into target repo
  1003. var args = args || {
  1004. folder : 'server'
  1005. , remotebase : 'http://git.bbh/chess/'
  1006. , targetrepo : 'elixir-server'
  1007. }
  1008. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  1009. , inherit: true, shell: true
  1010. , env: process.env
  1011. , runas: processedArgs.runas
  1012. }
  1013. var cmdseq = [
  1014. // git checkout -b feature/merge-old-project
  1015. // git remote add src-project ../src-project
  1016. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  1017. ]
  1018. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e); throw 'failed' })
  1019. }
  1020. , 'filter-branch' : function(preservefolder, repo){
  1021. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  1022. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  1023. // Preserve a specific folder.
  1024. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  1025. /*
  1026. git clone repo reposplit
  1027. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  1028. git remote rm origin
  1029. */
  1030. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  1031. }
  1032. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  1033. // // Merge repo2 into a subfolder in repo1
  1034. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  1035. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  1036. // /*
  1037. // cd repo1
  1038. // git remote add -f tempmergesource ../{{mergesource}}/.git
  1039. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  1040. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  1041. // git commit
  1042. // // Repair History
  1043. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  1044. // #!/usr/bin/env bash
  1045. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  1046. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  1047. // subdir=server
  1048. // git filter-branch --tree-filter '
  1049. // first='"$first"'
  1050. // last='"$last"'
  1051. // subdir='"$subdir"'
  1052. // log_file=/tmp/filter.log
  1053. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  1054. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  1055. // echo "=== $GIT_COMMIT: making changes"
  1056. // files=$(git ls-tree --name-only $GIT_COMMIT)
  1057. // mkdir -p $subdir
  1058. // for i in $files; do
  1059. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  1060. // done
  1061. // else
  1062. // echo "=== $GIT_COMMIT: ignoring"
  1063. // fi \
  1064. // >> $log_file
  1065. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  1066. // status=0 # tell tree-filter never to fail
  1067. // '
  1068. // git remote rm tempmergesource
  1069. // */
  1070. // // better alternative for history
  1071. // /**
  1072. // *
  1073. // git clone git@server.com:old-project.git
  1074. // git clone git@server.com:new-project.git
  1075. // cd old-project
  1076. // mkdir old-project
  1077. // git mv !(old-project) old-project
  1078. // ls -la and gt mv hidden files ....
  1079. // git commit -a -S -m “Moving old project into its own subdirectory”
  1080. // cd ../new-project
  1081. // git remote add old-project ../old-project
  1082. // git fetch old-project
  1083. // git checkout -b feature/merge-old-project
  1084. // git merge -S --allow-unrelated-histories old-project/master
  1085. // git push origin feature/merge-old-project
  1086. // git remote rm old-project
  1087. // */
  1088. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  1089. // }
  1090. , 'pull' : (label) => {
  1091. // Usage :
  1092. // elxr pull -- Defaults to run config
  1093. return elxr.getpulltask(selectedinstance)()
  1094. }
  1095. , 'isInstalled': () => {
  1096. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  1097. console.log(processedArgs._[1] + ' exists.')
  1098. return true;
  1099. });
  1100. }
  1101. , 'c' : ()=>{
  1102. }
  1103. , 'i' : () => {
  1104. var tasks = []
  1105. // tasks.push(op['pull']);
  1106. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
  1107. tasks.push(op['use'])
  1108. if (!__isElevated) {
  1109. tasks.push(op['npmi'])
  1110. }
  1111. // var tasksdefs = [
  1112. // ['elxr', ['pull']]
  1113. // , ['elxr', ['use', 'elixir']]
  1114. // , ['elxr', ['npmi']]
  1115. // ]
  1116. // tasksdefs.forEach(tasksdef=>{
  1117. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  1118. // })
  1119. return any(tasks);
  1120. }
  1121. , 'npmi': () => {
  1122. var tasks = [];
  1123. // Build fails without babel...
  1124. tasks.push(getShellTask(
  1125. 'npm',[ 'i', '-g', 'babel-cli' ]
  1126. ) )
  1127. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  1128. // npmbuildrepos = []
  1129. npmbuildrepos.forEach(repo => {
  1130. tasks.push(() => {
  1131. return nodeShellExec('npm', ['i --force'], {
  1132. inherit: true, shell: true
  1133. , cwd: instanceroot + '/' + repo
  1134. , env: process.env
  1135. , title: `npm i for ${repo}`
  1136. }).catch((e) => {
  1137. console.error('Ignoring Benign Error'); console.error(e);
  1138. }).then(() => {
  1139. console.log(`--npm run build for ${repo}--------------------`)
  1140. return nodeShellExec('npm', ['run build'], {
  1141. inherit: true, shell: true
  1142. , cwd: instanceroot + '/' + repo
  1143. , env: process.env
  1144. , title: `npm run build for ${repo}`
  1145. }).then(Tasq.then).catch(Tasq.catch)
  1146. })
  1147. })
  1148. })
  1149. return any(tasks).then(() => {
  1150. gitRepos.push('chess-server-lib/server');
  1151. gitRepos = gitRepos.concat(elevatedRunasRepos);
  1152. // gitRepos = [
  1153. // // 'bbhverse', 'serververse', 'elixir-server',
  1154. // // 'clientverse',
  1155. // 'client'
  1156. // ];
  1157. var rmtasks = []
  1158. var repotasks = []
  1159. var env = Object.assign({}, process.env)
  1160. delete env.NODE_ENV
  1161. gitRepos.forEach(repodef => {
  1162. rmtasks.push(
  1163. // () => {
  1164. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1165. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  1166. callshelltask(['rm', ['package-lock.json'], {
  1167. inherit: true, shell: true
  1168. , cwd: instanceroot + '/' + repodef.repo
  1169. , env: process.env
  1170. , title: `rm 'package-lock.json' for ${repodef.repo}`
  1171. }])
  1172. .then(()=>{
  1173. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1174. }).catch((e) => { console.error(e) })
  1175. // }
  1176. )
  1177. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  1178. repotasks.push(
  1179. () => {
  1180. console.log(`--npm i for ${repodef.repo}--------------------`)
  1181. var p = nodeShellExec('npm', ['i', '--force'], {
  1182. inherit: true, shell: true
  1183. , cwd: instanceroot + '/' + repodef.repo
  1184. , env
  1185. , title: `npm i for ${repodef.repo}`
  1186. }).then(Tasq.then).catch(Tasq.catch)
  1187. return p;
  1188. })
  1189. }
  1190. })
  1191. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  1192. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  1193. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  1194. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  1195. // Second time try also doesnt work.
  1196. // repotasks.push(
  1197. // () => {
  1198. // var env = Object.assign({}, process.env)
  1199. // delete env.NODE_ENV
  1200. // console.log(`--------------------second time npm i for client--------------------`)
  1201. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  1202. // // return nodeShellExec('npm', ['i --force'], {
  1203. // inherit: true, shell: true
  1204. // , cwd: instanceroot + '/' + 'client'
  1205. // , env
  1206. // , title: `npm i for client`
  1207. // }).then(Tasq.then).catch(Tasq.catch)
  1208. // })
  1209. var bowerRepos = [{ repo : 'client'}]
  1210. bowerRepos.forEach(repodef => {
  1211. repotasks.push(() => {
  1212. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
  1213. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  1214. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  1215. inherit: true, shell: true
  1216. , cwd: instanceroot + '/' + repodef.repo
  1217. , env: process.env
  1218. , title: `bower i for ${repodef.repo}`
  1219. }).then(Tasq.then).catch(Tasq.catch)
  1220. return p;
  1221. })
  1222. })
  1223. // console.log('rmtasks.length : ' + rmtasks.length)
  1224. return Promise.all(rmtasks).then(() => any(repotasks));
  1225. }).catch(e => {
  1226. console.error(e)
  1227. }).finally(statuslog.finally)
  1228. }
  1229. , 'start': (label) => {
  1230. console.log('Starting Elixir Server.');
  1231. var env = Object.assign({}, process.env); // Shallow clone it.
  1232. // console.dir(env)
  1233. env.NODE_ENV = process.env.NODE_ENV || 'development';
  1234. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  1235. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  1236. // cmd = 'node'
  1237. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
  1238. var childPromise = nodeShellExec(...cmd, {
  1239. // inherit : true,
  1240. shell: true,
  1241. detached: true,
  1242. stdio: 'ignore',
  1243. cwd: instanceroot + '/' + 'elixir-server'
  1244. , env: env
  1245. })
  1246. var child = childPromise.process;
  1247. if (typeof child.pid !== 'undefined') {
  1248. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1249. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  1250. encoding: 'utf8'
  1251. })
  1252. }
  1253. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  1254. // inherit : true,
  1255. // shell: true, detached: true,
  1256. // cwd : 'qms/server',
  1257. // env: env,
  1258. // shell : true
  1259. // })
  1260. // nodeShellExec('ember', ['s'], {
  1261. // // inherit : true,
  1262. // shell: true, detached: true,
  1263. // cwd : 'client/',
  1264. // env: env
  1265. // })
  1266. console.log('Starting Elixir Client Host.');
  1267. var cmd = ['ember', ['s']]
  1268. var childPromise = nodeShellExec(...cmd, {
  1269. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  1270. // PB : TODO -- ember debugging.
  1271. // inherit : true,
  1272. shell: true,
  1273. detached: true,
  1274. stdio: 'ignore',
  1275. cwd: instanceroot + '/' + 'client'
  1276. , env: env
  1277. })
  1278. // .catch(e=>console.error(e))
  1279. child = childPromise.process;
  1280. if (typeof child.pid !== 'undefined') {
  1281. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1282. fs.writeFileSync('.client.server.pid', child.pid, {
  1283. encoding: 'utf8'
  1284. })
  1285. }
  1286. }
  1287. , 'stop': (label) => {
  1288. const kill = require('tree-kill');
  1289. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  1290. encoding: 'utf8'
  1291. })
  1292. fs.unlinkSync('.elixir-server.elixir.server.pid')
  1293. console.log(serverPid)
  1294. kill(serverPid)
  1295. serverPid = fs.readFileSync('.client.server.pid', {
  1296. encoding: 'utf8'
  1297. })
  1298. fs.unlinkSync('.client.server.pid')
  1299. console.log(serverPid)
  1300. kill(serverPid)
  1301. }
  1302. , 'model' : () => {
  1303. if (__isElevated) {
  1304. var tasks = [
  1305. () => {
  1306. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  1307. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  1308. inherit: true, shell: true
  1309. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  1310. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  1311. , env: process.env
  1312. }).catch((e) => { console.error(e) })
  1313. return p;
  1314. }
  1315. ];
  1316. return any(tasks).then(() => {
  1317. fs.writeFileSync('run.done', 'success')
  1318. }).catch(() => {
  1319. fs.writeFileSync('run.done', 'error')
  1320. })
  1321. }
  1322. else return op['runas']()
  1323. }
  1324. , 'use' : () => {
  1325. // use a certain named instance.
  1326. // Eg :
  1327. // 1) elxr use elixir
  1328. // 2) elxr use cihsr
  1329. // If environment is not specified defaults to development.
  1330. // 1) NODE=test elxr use elixir
  1331. /*// Steps
  1332. 1) Delete Config and Data symlinks
  1333. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  1334. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  1335. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1336. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  1337. */
  1338. var runconfig = { NODE_ENV: selectedinstance.node_env }
  1339. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  1340. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  1341. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  1342. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  1343. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  1344. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  1345. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  1346. if (existsSync('config') && existsSync('data')){
  1347. return
  1348. }
  1349. }
  1350. var tasks = [
  1351. () => {
  1352. if (existsSync('config')) {
  1353. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  1354. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  1355. return p;
  1356. }
  1357. else return Promise.resolve(true);
  1358. },
  1359. () => {
  1360. if (existsSync('data')) {
  1361. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  1362. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  1363. return p;
  1364. }
  1365. else return Promise.resolve(true);
  1366. },
  1367. ];
  1368. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  1369. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  1370. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  1371. // console.log(process.env.cwd)
  1372. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  1373. // Maps an environment to a branch. Not required if the branch is appropriately named.
  1374. var checkoutMap = { 'development': 'master' }
  1375. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  1376. var performPullOrCloneForBranch = (def)=>{
  1377. var promise = Promise.resolve(true)
  1378. if (!branch) {
  1379. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1380. promise = nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{ branch = __branch})
  1381. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1382. }
  1383. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e )})
  1384. }
  1385. var performCloneAndCheckout = null;
  1386. // cant use git checkout -b it fails when branch already exists.
  1387. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1388. return performPullOrCloneForBranch(def).then(()=>{
  1389. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1390. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1391. // inherit : true, shell: true,
  1392. cwd: instanceroot + '/' + def.repo
  1393. // , stdio : ignore // Use when we want to silence output completely.
  1394. , runas: processedArgs.runas
  1395. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  1396. }).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 } })
  1397. })
  1398. }
  1399. // var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  1400. // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  1401. var elevatedqueue = [];
  1402. var enqueueOnce = (queue, task, def) => {
  1403. var found = queue.find(element => {
  1404. var keys = Object.keys( element )
  1405. for(var k=0; k < keys.length; k++) {
  1406. if(element[keys[k]] !== def[k]) return false;
  1407. }
  1408. })
  1409. queue.push(function(){ return task(this)}.bind(def));
  1410. }
  1411. var enqueue = (queue, task, def) => {
  1412. queue.push(function(){ return task(def)}.bind(def));
  1413. }
  1414. var mergeSources = {
  1415. 'development': null,
  1416. 'test': 'master',
  1417. 'production': 'master'
  1418. }
  1419. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1420. // Checkout is reduced to pull provided the current branch is the targetbranch
  1421. if(branch === mergesource) performCheckout = (def) => {
  1422. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1423. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  1424. if(branch === __branch) return performCloneAndCheckout(def)
  1425. return performPullOrCloneForBranch(def)
  1426. })
  1427. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1428. }
  1429. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  1430. var performPullAll = (def) => {
  1431. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1432. return nodeShellExec('git', ['pull', '--all'], {
  1433. // inherit : true, shell: true,
  1434. cwd: instanceroot + '/' + def.repo
  1435. , runas: processedArgs.runas
  1436. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  1437. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  1438. }
  1439. var excludeCheckouts = Object.assign(exludeMergeRepos)
  1440. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  1441. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  1442. var performMerge = (def) => {
  1443. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  1444. return nodeShellExec('git', ['merge', mergesource], {
  1445. inherit: true, shell: true,
  1446. cwd: instanceroot + '/' + def.repo
  1447. , runas: processedArgs.runas
  1448. }).catch((e) => { console.error(e) })
  1449. }
  1450. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
  1451. // var performRepoOperation = function(def) {
  1452. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  1453. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  1454. // }
  1455. return any(tasks).then(() => {
  1456. var pr = Promise.resolve(true)
  1457. if (!__isElevated) {
  1458. pr = op['runas']()
  1459. return pr.then(()=>{
  1460. //target is the env is we specify in elxr use command. Default is dev
  1461. //Switch to target branch
  1462. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  1463. // pull or clone target branch
  1464. .then(() => {
  1465. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1466. return any(gitRepos.map((repo) => performPullAll(repo)))
  1467. })
  1468. // switch to source branch
  1469. .then( () => {
  1470. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  1471. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  1472. })
  1473. //Pull on merge source branch
  1474. .then( () => {
  1475. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1476. return any(gitRepos.map((repo) => performPullAll(repo)))
  1477. })
  1478. //Switch to target branch
  1479. .then( () => {
  1480. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1481. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  1482. })
  1483. .then( //Merge source branch to target branch
  1484. () => {
  1485. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1486. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
  1487. })
  1488. })
  1489. }
  1490. else {
  1491. tasks = [
  1492. () => {
  1493. // Use junctions to avoid npm package issues
  1494. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  1495. inherit: true, shell: true
  1496. , cwd : instanceroot
  1497. , env: process.env
  1498. }).catch((e) => { console.error(e) })
  1499. return p;
  1500. }
  1501. ];
  1502. if (processedArgs._[1]) {
  1503. tasks = tasks.concat(
  1504. [
  1505. () => {
  1506. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  1507. inherit: true, shell: true
  1508. , cwd : instanceroot
  1509. , env: process.env
  1510. }).catch((e) => { console.error(e) })
  1511. return p;
  1512. }
  1513. ]
  1514. )
  1515. }
  1516. return any(tasks).then(()=>{
  1517. // checkout target branch
  1518. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1519. // pull or clone target branch
  1520. .then(() => {
  1521. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1522. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  1523. })
  1524. // switch to source branch
  1525. .then( () => {
  1526. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1527. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  1528. })
  1529. //Pull on merge source branch
  1530. .then( () => {
  1531. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1532. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  1533. })
  1534. //Switch to target branch
  1535. .then( () => {
  1536. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1537. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1538. })
  1539. .then( //Merge source branch to target branch
  1540. () => {
  1541. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1542. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
  1543. })
  1544. .then(() => {
  1545. fs.writeFileSync('run.done', 'success')
  1546. }).catch(() => {
  1547. fs.writeFileSync('run.done', 'error')
  1548. })
  1549. })
  1550. }
  1551. }).catch(() => {
  1552. fs.writeFileSync('run.done', 'error')
  1553. })
  1554. // Antibiotic stewardship program.
  1555. // 1st use is fine.
  1556. // Max vials dispense
  1557. // 2nd use Pharmacy needs justification Form.
  1558. // Approval after a certain period of time.
  1559. }
  1560. , 'g': () => {
  1561. if (processedArgs.h) {
  1562. console.log('elxr g [modelname] => generate a model named [modelname]');
  1563. console.log('elxr g => regenerate all known models');
  1564. return
  1565. }
  1566. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1567. // console.log('Starting directory: ' + process.cwd());
  1568. // try {
  1569. // child = child.on('close', () => { process.chdir(label) } );
  1570. // console.log('New directory: ' + process.cwd());
  1571. // }
  1572. // catch (err) {
  1573. // console.log('chdir: ' + err);
  1574. // }
  1575. // child.on('close', function(){
  1576. // var options = {
  1577. // shell : true
  1578. // , inherit : true
  1579. // // , cwd : '' + process.cwd
  1580. // // , env : process.env
  1581. // };
  1582. // nodeShellExec('git', ['init'], { inherit : true});
  1583. if (0) {
  1584. // PB : TODO -- Special google chrome profile for tests etc.
  1585. nodeShellExec('pwd', { inherit: true });
  1586. // /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"
  1587. // "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
  1588. // "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
  1589. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1590. "--profile-directory=Profile 1"
  1591. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1592. }
  1593. // nodeShellExec('npm', ['init', '-y'], options);
  1594. // nodeShellExec('npm', ['init', '-y'], options);
  1595. // })
  1596. var g = {
  1597. 'client': () => {
  1598. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  1599. console.info('Creating new ember client named : ' + processedArgs._[2]);
  1600. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1601. stdio: ['pipe', process.stdout, process.stderr],
  1602. inherit: true,
  1603. shell: true,
  1604. cwd: path.dirname(__dirname),
  1605. env: env
  1606. })
  1607. },
  1608. 'modelr': () => {
  1609. var tasks = [
  1610. () => {
  1611. var p = nodeShellExec('"ember"', [
  1612. 'g'
  1613. , 'modelr'
  1614. , processedArgs._[2]], {
  1615. inherit: true, shell: true, env: process.env
  1616. }).then(() => {
  1617. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  1618. return true;
  1619. }).catch((e) => { console.error(e) })
  1620. return p;
  1621. },
  1622. () => {
  1623. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1624. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  1625. chromeprefs = JSON.parse(chromeprefs)
  1626. var previous = chromeprefs.download.default_directory;
  1627. var parentDir = path.dirname(__dirname);
  1628. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1629. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1630. // PB : TODO -- detect where chrome is installed.
  1631. // PB : TODO -- set the download dir to the place where files are needed.
  1632. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1633. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1634. , '--profile-directory="chess"'
  1635. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1636. inherit: true, shell: true
  1637. , env: process.env
  1638. }).then(() => {
  1639. chromeprefs.download.default_directory = previous;
  1640. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1641. return true;
  1642. }).catch((e) => { console.error(e) })
  1643. return p;
  1644. }
  1645. ,
  1646. () => {
  1647. console.log('Browser process should have closed here....')
  1648. return true;
  1649. }
  1650. ]
  1651. any(tasks)
  1652. }
  1653. }
  1654. g[processedArgs._[1]]();
  1655. }
  1656. , 'create' : () => {
  1657. return createInstance(selectedinstance) }
  1658. , 'httpget' : () => {
  1659. // HTTPAPI.get({
  1660. // hostname: 'git.bbh',
  1661. // // port: 443,
  1662. // protocol : 'http:',
  1663. // path: '/',
  1664. // method: 'GET'
  1665. // }, function(data){ console.log(data)}, function(error){ console.log(error)} )
  1666. return createInstance(selectedinstance)
  1667. }
  1668. , 'getuser' : ()=>{
  1669. return prerequisites.git.getuser().then(u=>{ console.log(u)})
  1670. }
  1671. }
  1672. var util = require('util');
  1673. var cliname = 'elxr';
  1674. var ver = '1.1';
  1675. var readme = `
  1676. Command syntax examples
  1677. elxr
  1678. Displays help. Same as elxr h
  1679. elxr i
  1680. Runs interactive propmts to help choose installation options.
  1681. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  1682. General command syntax.
  1683. Eg: NODE_ENV=development elxr pull elixir
  1684. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  1685. The specific cmd defines what the value is interpreted as.
  1686. There are several cmds that do not require an {{instancename}} parameter.
  1687. Eg: elxr remote remove origin
  1688. Git operations or passthrough external commands on all repository folders in you working directory.
  1689. Main objectives.
  1690. elxr cli is a wrapper around other shell commands and api based operations.
  1691. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  1692. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  1693. `;
  1694. var help = `
  1695. ${readme}
  1696. # list of commands... please refer dveloper documentation for ${cliname}
  1697. \r\n\t${
  1698. Object.keys(op).join('\r\n\t')
  1699. }
  1700. `;
  1701. var elxr = {
  1702. help() {
  1703. return chalk.cyanBright(`
  1704. -------------------------------------------------------------------------------
  1705. *** BBH Elixir ***
  1706. -------------------------------------------------------------------------------
  1707. elxr ${ver}
  1708. A cli tool for chess
  1709. ${help}
  1710. -------------------------------------------------------------------------------
  1711. `)
  1712. }
  1713. , info() {
  1714. return chalk.cyanBright(`
  1715. -------------------------------------------------------------------------------
  1716. *** BBH Elixir ***
  1717. -------------------------------------------------------------------------------
  1718. elxr ${ver}
  1719. A cli tool for chess
  1720. -------------------------------------------------------------------------------
  1721. `)
  1722. }
  1723. , getpulltask(args){
  1724. // def can be an instance config
  1725. // Or an object with many repos and elevated repos
  1726. // Or a single repo ( Either Elevated or normal. )
  1727. // USAGE
  1728. // elxr pull elixir origin master
  1729. // elxr pull
  1730. // not all remote branches are setup to be tracked locally (respective remotes and branches).
  1731. // pull --all is useless. As it fetches all remotes and branches but only merges current branch.
  1732. // apart from remote tracking branches We are interested in pulling from all remotes and relavant branches.
  1733. // The branch pipline should feed back to master
  1734. // master -> test -> stage -> release[nnnn] -> production
  1735. // (master) <= git merge [all remotes] production && git merge [all remotes] release[nnnn]
  1736. // git merge [all remotes] stage && git merge [all remotes] test && git merge [all remotes] master
  1737. var __args = {
  1738. remotename : args.remotename|| processedArgs._[2]
  1739. , url : args.url || processedArgs._[3]
  1740. , branch : args.branch || processedArgs._[4] // If branch not specified opearte on the current branch of each working directorys
  1741. }
  1742. // var commands = [
  1743. // // ['git', ['checkout', __args.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]]
  1744. // ,
  1745. // ]
  1746. // var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  1747. // var pullCmd = [ gitbash
  1748. // , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  1749. // , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  1750. var def = args || {
  1751. repos : selectedinstance.repos,
  1752. elevated : selectedinstance.elevated
  1753. }
  1754. var elevatedpulltasks = null;
  1755. if(def.repo) {
  1756. // Single repo case.
  1757. if(def.repo.requiresElevation) {
  1758. elevatedpulltasks = function() {
  1759. return performPull(def.repo).then(() => {
  1760. return true;
  1761. }).catch((e) => {
  1762. console.error(e)
  1763. })
  1764. }
  1765. return
  1766. }
  1767. else {
  1768. var regularpulltasks = function(){
  1769. var pendingpulls = [];
  1770. pendingpulls.push(performPull(def.repo))
  1771. return Promise.all(pendingpulls).finally(Traq.finally)
  1772. }
  1773. }
  1774. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1775. else return getTaskWithoutElevation({ regularpulltasks})
  1776. }
  1777. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  1778. console.dir(def)
  1779. var env = Object.assign({}, process.env); // Shallow clone it.
  1780. console.log('Running exlr pull : ' + path.dirname(__dirname))
  1781. var useGitPull = processedArgs.useGitPull || false;
  1782. if(def.elevated || def.repos) {
  1783. if(def.elevated) def.requiresElevation = true;
  1784. else delete def.requiresElevation;
  1785. }
  1786. else {
  1787. if(def.requiresElevation) def.elevated = [def]
  1788. else def.repos = [def]
  1789. }
  1790. var regularpulltasks = function(){ return Promise.resolve(true) }
  1791. if(def.elevated){
  1792. elevatedpulltasks = function() {
  1793. return any(def.elevated.map((def) => performPull(def.repo))).then(() => {
  1794. return true;
  1795. }).catch((e) => {
  1796. console.error(e)
  1797. })
  1798. }
  1799. }
  1800. if(def.repos) {
  1801. var regularpulltasks = function(){
  1802. var pendingpulls = [];
  1803. def.repos.forEach((def) => { pendingpulls.push(performPull(def.repo)) })
  1804. return Promise.all(pendingpulls).finally(Traq.finally)
  1805. }
  1806. }
  1807. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1808. else return getTaskWithoutElevation({ regularpulltasks})
  1809. }
  1810. }
  1811. function preworkerconfig(){
  1812. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  1813. gitRepos = selectedinstance.repos
  1814. // gitRepos = ['chess-server-lib'];
  1815. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  1816. elevatedRunasRepos = selectedinstance.elevated
  1817. // Repos that should excluded from merge for releases...
  1818. exludeMergeRepos = selectedinstance.exludeMergeRepos
  1819. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  1820. // mysql -u root -p db_name < drop_all_tables.sql
  1821. var mysql = '../xampp/mysql/bin/mysql'
  1822. var mysqldump = '../xampp/mysql/bin/mysqldump'
  1823. }
  1824. // The main elxr cli process
  1825. function elxrworker() {
  1826. var __runcmd = function (label) {
  1827. var distinquishedlabel = subcommandlabels[label] || label
  1828. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  1829. }
  1830. // --runas
  1831. if (processedArgs.runas) {
  1832. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  1833. return __runcmd('runas')
  1834. }
  1835. else return __runcmd(processedArgs.label || processedArgs._[0] || 'undefined');
  1836. }
  1837. // function acquireChoices(selectedinstance) {
  1838. // var hasconfig = false;
  1839. // console.warn(chalk.cyan(`
  1840. // -------------------------------------------------------------------------------
  1841. // Could not locate your preferred configuration (you may not specified it)
  1842. // You should fork the default chess configuration to customize and make it
  1843. // your own instance with a named config as
  1844. // {{yourowninstancename}}-config-{{yourchosenenvironment}}
  1845. // And then run this tool as follows
  1846. // NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  1847. // OR
  1848. // Run this tool with the following command to use a quick start default.
  1849. // elxr --default
  1850. // OR
  1851. // Choose one of the options below to run interactively.
  1852. // We will run your choice at the next prompt.
  1853. // -------------------------------------------------------------------------------
  1854. // `))
  1855. // var choices = getInteractionPoints(detectedinstanceoptions, __interactive_prompts)
  1856. // var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  1857. // return initinstances(selectedinstance)
  1858. // })
  1859. // // var prompt = cli.prompter;
  1860. // // return prompt.ask(`Choose an option :
  1861. // // d) Install the default chess instance.
  1862. // // => elxr i chess node_env=development --default
  1863. // // n) Create your custom new instance interactively
  1864. // // => elxr i {{instanceName}} node_env={{environment}}
  1865. // // i) Choose an instance and environment to install
  1866. // // => elxr i {{instanceName}} node_env={{environment}}
  1867. // // c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  1868. // // => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  1869. // // h) Help
  1870. // // q) Quit
  1871. // // Default <= d
  1872. // // : `).then((choice) => {
  1873. // // if (choice && choice === 'd' || !choice) {
  1874. // // processedArgs._[0] = 'i'
  1875. // // selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  1876. // // selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  1877. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  1878. // // }
  1879. // // else if (choice === 'h') {
  1880. // // processedArgs._[0] = 'h'
  1881. // // fs.writeFileSync('run.done', 'noop help');
  1882. // // console.log(elxr.help()); process.exit()
  1883. // // }
  1884. // // else if (choice === 'n' || choice === 'i') {
  1885. // // var p1 = cli.prompter;
  1886. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1887. // // processedArgs._[0] = 'i'
  1888. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  1889. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1890. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1891. // // if (choice === 'n') {
  1892. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  1893. // // console.warn(
  1894. // // chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  1895. // // process.exit();
  1896. // // }
  1897. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1898. // // selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1899. // // })
  1900. // // })
  1901. // // })
  1902. // // } else if (choice === 'c') {
  1903. // // var p1 = cli.prompter;
  1904. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1905. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  1906. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1907. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1908. // // return p1.ask(`Enter cmd :
  1909. // // p) pull
  1910. // // Default <= p
  1911. // // : `).then(function (cmd) {
  1912. // // if (!cmd || cmd === 'p') {
  1913. // // processedArgs._[0] = 'pull'
  1914. // // }
  1915. // // else processedArgs._[0] = cmd
  1916. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1917. // // selectedinstance.reposerver = reposerver || selectedinstance.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1918. // // })
  1919. // // })
  1920. // // })
  1921. // // })
  1922. // // } else {
  1923. // // 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.`));
  1924. // // fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  1925. // // fs.writeFileSync('run.done', 'noop quit');
  1926. // // process.exit()
  1927. // // }
  1928. // // })
  1929. // }
  1930. var mergeObjByKey = function(arrOfObjs, keyName) {
  1931. var keyedDistinct = {}
  1932. var distinctArrOfObjs = []
  1933. arrOfObjs.forEach( o => {
  1934. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o)
  1935. })
  1936. Object.keys(keyedDistinct).forEach(key => {
  1937. distinctArrOfObjs.push( utils.assign( ...keyedDistinct[key] ) ) // PB : TODO -- Shallow use utils.assign
  1938. })
  1939. return distinctArrOfObjs;
  1940. }
  1941. var cacheWriteInstanceConfig = function(chessinstances){
  1942. var instanceName = chessinstances['current_run'].instanceName;
  1943. var node_env = chessinstances['current_run'].node_env;
  1944. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos, 'repo') ;
  1945. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated, 'repo') ;
  1946. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  1947. }
  1948. var acquireConfig = function (selected) {
  1949. var configrepo = selected.instanceName + '-config-' + selected.node_env;
  1950. return performPull(configrepo).then(() => {
  1951. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  1952. selectedinstance = require(manifestpath)( null, selectedinstance)
  1953. // Config from server always override merges into selection except for the current selection.
  1954. // PB : TODO -- utils.assign Array merges are non-distinct...
  1955. if(!selectedinstance.repos[0].repo) {
  1956. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  1957. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  1958. }
  1959. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  1960. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  1961. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  1962. }
  1963. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = utils.assign(selected, selectedinstance)
  1964. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  1965. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  1966. cacheWriteInstanceConfig(chessinstances)
  1967. ENV.NODE_ENV = selectedinstance.node_env;
  1968. })
  1969. .catch((e) => {
  1970. console.error(e)
  1971. console.error('Config acquisition failed.')
  1972. })
  1973. }
  1974. var launchpath = path.normalize(process.cwd())
  1975. var thisscriptdir = path.normalize(__dirname); // PB : TODO -- Thisscriptdir could be dislocated when run as a standalone file... We need to detect this where and how we were run.
  1976. // The easisest would be to ask for a target directory and default to current dir....
  1977. var instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
  1978. // PB : TODO -- Embed this in the build instead of inlining it.
  1979. // Also attepmt to load from ../chess-config/...
  1980. var __default = ((name, options)=>{
  1981. // Default set of users in main repos.
  1982. var users = [
  1983. { username : `${options.username}`, password : `${options.password}` }
  1984. , { username : `chess` }
  1985. // , { username : `baptistdev`, password : 'encrypted' }
  1986. // , { username : `guest`, password : 'encrypted' }
  1987. ]
  1988. // ${options.reposerver} should be used to lookup current config.
  1989. // User can always add more branches and remotes as needed. Mainifest only occupies
  1990. // well defined namespaces
  1991. var remotes = {
  1992. // these are both fetch and push remotes. Use push - remotes to override push.
  1993. 'chess' : { path : `/chess/`, push : 'no-pushing' }
  1994. // Multiple urls dont tell us the current origin which may be
  1995. // different based on currently available/accessible based on device and client.
  1996. // We just treat them as different remotes and merge as needed.
  1997. //
  1998. , 'origin' : { path : `/${options.username}/` }
  1999. , 'origin-public' : { path : `/${options.username}/` }
  2000. , 'origin-unc' : { path : `/${options.username}/` }
  2001. // , { `${options.username}` : `https://git.bbh.org.in/${options.username}/elxr.git` }
  2002. }
  2003. // , 'fetch-remotes' : [] // Multiple fetch remotes are not supported by git.
  2004. // We therefore need to use
  2005. // - a pullall
  2006. // - or branch alias for multiple remote branch tracking branch strategy.
  2007. // -- This is however limited to corresponding branch names
  2008. // tracking branches.
  2009. // We at least need one branch for each remote that we wish to track.
  2010. // , 'tracking-branches' : [
  2011. // { master : ['origin/master', 'chess/master'] }
  2012. // ]
  2013. var reposerverinstances = {
  2014. 'http://git.bbh' : { users, remotes }
  2015. , 'https://git.bbh.org.in' : { users, remotes, external : true }
  2016. , '//172.16.0.27/repos' : { users, remotes }
  2017. , 'https://github.com' : {
  2018. // We host a miniaml set of repositories in github.
  2019. get users() { return [{ username : `${this.username}` }]}, username : `baptistdev`
  2020. , remotes : { get 'baptistdev-public'() { return {path : `/${this.username}/`, push : 'no-pushing'} }
  2021. // , Add other remotes here.
  2022. }
  2023. , external : true, public : true
  2024. }
  2025. }
  2026. return {
  2027. reposervers : Object.keys(reposerverinstances)
  2028. , reposerverinstances
  2029. // Common baseline repos for all chess instances.
  2030. , repos : [
  2031. { repo : 'ember-masonry-grid' /*, branch : master*/ } // Default need not be specified.
  2032. , { repo : 'bbhverse' }
  2033. , { repo : 'clientverse' }
  2034. , { repo : 'serververse' }
  2035. , { repo : 'elxr' }
  2036. , { repo : 'ember-searchable-select' }
  2037. , { repo : 'loopback-component-jsonapi' }
  2038. , { repo : 'loopback-jsonapi-model-serializer' }
  2039. , { repo : 'loopback-connector-mysql' }
  2040. , { repo : 'loopback-connector-ds' }
  2041. , { repo : 'chess-server-lib' }
  2042. , { repo : 'ember-service-worker' }
  2043. , { repo : 'ember-service-worker-asset-cache' }
  2044. , { repo : 'ember-service-worker-cache-fallback' }
  2045. , { repo : 'ember-service-worker-index' }
  2046. , { repo : 'ember-sw-client-route' }
  2047. , { repo : 'global-this' }
  2048. ]
  2049. // PB : TODO -- lighter defaults for lite new instance creation..
  2050. , repos: [
  2051. { repo : 'setup' }
  2052. , { repo : 'elxr' }
  2053. , { repo : 'loopback-connector-mysql' }
  2054. , { repo : 'loopback-jsonapi-model-serializer' }
  2055. , { repo : 'loopback-component-jsonapi' }
  2056. , { repo : 'ember-service-worker' }
  2057. , { repo : 'ember-service-worker-asset-cache' }
  2058. , { repo : 'ember-service-worker-cache-fallback' }
  2059. , { repo : 'ember-service-worker-index' }
  2060. , { repo : 'ember-sw-client-route' }
  2061. ]
  2062. , elevated : [ ]
  2063. , exludeMergeRepos : { }
  2064. }
  2065. })(
  2066. '__default' // name
  2067. , { username : 'guest', instanceName : 'chess', node_env : 'development', reposerver : 'https://git.bbh.org.in' } // options
  2068. )
  2069. // We first load the default and then override with a runconfig if it exists else we override with the interactive prompts.
  2070. // Then acquire and reload and replace this default.
  2071. var hasElxr = function(path, options, cb) {
  2072. // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
  2073. options = options || {};
  2074. var tasks = [
  2075. '/elxr' // Is there a subfolder named elxr
  2076. , '/elxr/.git' // which is self git repository
  2077. , '/elxr/.elxr' // and has .elxr subfolder
  2078. , '/elxr/.elxr/' + __ALIAS__STAMP__ // Which has our stamp.
  2079. ]
  2080. if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
  2081. var value = existsFolderSync(path + tpath);
  2082. return { value, done : acc && !value };
  2083. }).value }
  2084. if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
  2085. var value = existsFolderSync(path + tpath);
  2086. return { value, done : acc && !value };
  2087. }).value );
  2088. return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
  2089. var value = existsFolderSync(path + tpath);
  2090. return { value, done : acc && !value };
  2091. }).value);
  2092. }
  2093. var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); }
  2094. var detectfromroot = function(root){
  2095. return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(root) ) }
  2096. }
  2097. var detectinstances = function () {
  2098. console.log(`launchpath = ${launchpath}`)
  2099. console.log(`thisscriptdir = ${thisscriptdir}`)
  2100. // PB : TODO -- !Postpone this.
  2101. console.log(`instanceroot = ${instanceroot}`) // Not yet confirmed...
  2102. // Note : Paths should already be normalized fefore this.
  2103. var root = instanceroot;
  2104. var detected = { root };
  2105. var instanceoptions = [clioverrides]
  2106. return hasElxr(launchpath).then( (elxrCliExists) => {
  2107. // We need a reference to the root director for elxr cli to be properly oriented.
  2108. if (( elxrCliExists && path.normalize(launchpath + '/elxr')) === thisscriptdir) {
  2109. // We were run from the proper root with elxr cli in the subfolder.
  2110. instanceroot = root = launchpath;
  2111. instanceoptions.splice( 0, 0, detected = { root })
  2112. instanceoptions.splice( 0, 0, detectfromroot(root))
  2113. }
  2114. else {
  2115. if(path.normalize(launchpath + '/elxr') === thisscriptdir) {
  2116. // elxrCliExists is false -- and yet thiscriptdir is still proper.
  2117. // PB : TODO -- Maybe a warning / abort if for some reason this scriptdir should not be taken over...
  2118. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.')
  2119. instanceroot = root = launchpath;
  2120. instanceoptions.splice( 0, 0, detected = { root })
  2121. instanceoptions.splice( 0, 0, detectfromroot(root))
  2122. }
  2123. else if (launchpath === thisscriptdir) {
  2124. var parentHasElxr = hasElxrSync(launchpath + '/..')
  2125. // PB : TODO -- verify if we have .elxr folder in the parent...
  2126. if(!parentHasElxr) {
  2127. // ! thisscriptdir is not elxr.
  2128. console.error('Invalid run location in subfolder that looks like elxr. We should probably abort as elxr will not sync.')
  2129. }
  2130. // Same directory doesn't mean we are being run from elxr sub directory.
  2131. // In standalone build script we may or not be in the same location.
  2132. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  2133. // Unbuilt therefore we are in the elxr sub directory.
  2134. instanceroot = root = path.normalize(launchpath + '/..');
  2135. instanceoptions.splice( 0, 0, detected = { root });
  2136. instanceoptions.splice( 0, 0, detectfromroot(root));
  2137. }
  2138. else {
  2139. // Built version.
  2140. // We could have been run from the elxr subfolder. Highly likely that the built version isn't the full elxr.
  2141. if(parentHasElxr) {
  2142. // Built version was run from the full elxr subfolder. Should work
  2143. // PB : TODO -- but we should switch to the full version...
  2144. instanceroot = root = path.normalize(launchpath + '/..');
  2145. instanceoptions.splice( 0, 0, detected = { root })
  2146. instanceoptions.splice( 0, 0, detectfromroot(root))
  2147. }
  2148. else {
  2149. instanceroot = root = launchpath;
  2150. instanceoptions.splice( 0, 0, detected = { root })
  2151. instanceoptions.splice( 0, 0, detectfromroot(root))
  2152. // Assume current launchpath is a new instance and create.
  2153. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  2154. // if(clioverrides.instanceName) {
  2155. // if(clioverrides.node_env) {
  2156. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  2157. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  2158. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  2159. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  2160. // // eg : floder name can be elixir01 but instance name is elixr
  2161. // }
  2162. // else {
  2163. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + 'development')
  2164. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  2165. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  2166. // }
  2167. // }
  2168. // else {
  2169. // instanceroot = root = launchpath;
  2170. // if(clioverrides.node_env) {
  2171. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  2172. // instanceoptions.splice( 0, 0, detectfromroot(root))
  2173. // }
  2174. // else {
  2175. // // Nothing was specified... We only have one option from root.
  2176. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  2177. // }
  2178. // }
  2179. }
  2180. }
  2181. }
  2182. else {
  2183. if(elxrCliExists) {
  2184. instanceroot = root = launchpath;
  2185. instanceoptions.splice( 0, 0, detected = { root })
  2186. instanceoptions.splice( 0, 0, detectfromroot(root))
  2187. }
  2188. }
  2189. }
  2190. instanceroot = detected.root
  2191. __default.root = root;
  2192. clioverrides.root = clioverrides.root || root;
  2193. // Resolves empty array when No known instances detected.
  2194. return Promise.resolve(instanceoptions)
  2195. })
  2196. }
  2197. var getReconfirmAll = ()=>{return { instanceName : true, instanceType : true, reposerver : true, username : true, password : true } }
  2198. if(clioverrides.reconfirm) {
  2199. var reconfirm = getReconfirmAll()
  2200. }
  2201. else { var reconfirm = {}; }
  2202. var shouldPrompt = function(k, mustPrompt, target){
  2203. return ((mustPrompt[k] !== undefined && mustPrompt[k] !== null) && target[k] !== mustPrompt[k]
  2204. || (mustPrompt[k] === undefined || mustPrompt[k] === null) && (target[k] === undefined || target[k] === null)
  2205. || reconfirm[k])
  2206. }
  2207. var getBoundEachPrompt = function(target, mustPrompt, promptables, choices, promptsfilter) {
  2208. return function(prompts, k, i, a){
  2209. // No local instances config found. We use a default initialized instance available in selectedinstance
  2210. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  2211. // PB : TODO -- selectedinstance === __default check to prompt everything...
  2212. if( shouldPrompt(k, mustPrompt, target) ) {
  2213. delete reconfirm[k];
  2214. // console.log(k)
  2215. // console.dir(mustPrompt); //console.dir(target)
  2216. prompts.push(async ()=>{
  2217. // PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
  2218. // We take a snapshot... Shallow.. !! If required deep should be used based on use case.
  2219. // If latest altered state is required we can reerence this directly.
  2220. // var asyncthis = Object.assign(this);
  2221. promptables[k].choices = choices[k]
  2222. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  2223. return await target[k]
  2224. })
  2225. }
  2226. delete mustPrompt[k]
  2227. return prompts
  2228. }
  2229. }
  2230. var __interactive_prompts = function( target, choices, promptsfilter ){
  2231. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  2232. var interactionpoints = {
  2233. runchoice : {
  2234. label :
  2235. `Choose an option :
  2236. d) Install the default chess instance.
  2237. => elxr i chess node_env=development --default
  2238. n) Create your custom new instance interactively
  2239. => elxr i {{instanceName}} node_env={{environment}}
  2240. i) Choose an instance and environment to install
  2241. => elxr i {{instanceName}} node_env={{environment}}
  2242. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  2243. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  2244. h) Help
  2245. q) Quit
  2246. : `
  2247. , choices : []
  2248. , defaultchoice : 'c'
  2249. , interpret : function(choice){
  2250. var interpret_map = {
  2251. d : function(){
  2252. processedArgs._[0] = 'i'
  2253. target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  2254. target.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  2255. target.reposerver = 'https://git.bbh.org.in'
  2256. }
  2257. , n : function() { processedArgs._[0] = 'i' }
  2258. , i : function() { processedArgs._[0] = 'i' }
  2259. , c : async function() {
  2260. Object.defineProperty(this, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  2261. label : `Enter cmd :
  2262. p) pull
  2263. Default <= p
  2264. : `
  2265. , defaultchoice : 'pull'
  2266. }
  2267. ));
  2268. var cmd = await target['cmd'];
  2269. if (!cmd || cmd === 'p') { target['cmd'] = processedArgs._[0] = 'pull' }
  2270. else target['cmd'] = processedArgs._[0] = cmd
  2271. return cmd;
  2272. }
  2273. , h : function() { console.log(elxr.help()); process.exit() } // PB : TODO -- Why do we need log.
  2274. , q : function() { process.exit() }
  2275. }
  2276. var __interpreter = interpret_map['c']
  2277. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  2278. if(interpret_map[choice]) __interpreter = interpret_map[choice];
  2279. return __interpreter.call(target)
  2280. }
  2281. }
  2282. , instanceName : { label : `Enter Instance Name ( <= ${target.instanceName || 'chess'} ) : `
  2283. , choices : choices['instanceName'], defaultchoice : 'chess'}
  2284. , instanceType : { label : `Enter Instance Type ( <= ${target.instanceType || 'development'} ) : `
  2285. , choices : choices['instanceType'], defaultchoice : 'development'}
  2286. , reposerver : { label : `Enter Instance Name ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `
  2287. , choices : choices['reposerver'], defaultchoice : 'https://git.bbh.org.in'}
  2288. , username : { label : `Enter User Id for ${target.reposerver} ( <= ${target.username || 'chess'} ) : `
  2289. , choices : choices['username'], defaultchoice : 'chess'}
  2290. , password : { label : `Enter Password for ${target.username} @ ${target.reposerver} ( <= ${target.password || ''} ) : `
  2291. , choices : choices['password'], defaultchoice : '***'}
  2292. , email : { label : `Enter Email for ${target.username} @ ${target.reposerver} ( <= ${target.email || ''} ) : `
  2293. , choices : choices['email'], defaultchoice : 'guest@bbh.org.in'}
  2294. }
  2295. function getPromptKeys() {
  2296. if(! (processedArgs.label || processedArgs._[0]) ) return Object.assign({}, interactionpoints);
  2297. return promptkeys
  2298. }
  2299. var eachPrompt = getBoundEachPrompt( target, getPromptKeys() , interactionpoints, choices, promptsfilter)
  2300. return Object.keys(promptsfilter || interactionpoints).reduce(eachPrompt, [])
  2301. }
  2302. var downloadsdir = '../Downloads';
  2303. var prerequisites = [
  2304. {
  2305. shellcmd: 'git',
  2306. name : 'git',
  2307. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  2308. , installer: 'Git-2.31.0-64-bit.exe'
  2309. , installcmd: ['cmd', ['/c', 'start',
  2310. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  2311. , '/VERYSILENT'
  2312. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  2313. ]]
  2314. , preinstallsteps: function() {
  2315. var steps = [
  2316. () => {
  2317. if (!existsSync(downloadsdir + '/' + this.installer)) {
  2318. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  2319. }
  2320. else return Promise.resolve(true)
  2321. }
  2322. ]
  2323. var prompts = this.getuser(null, ()=>{
  2324. // console.log('preinstallsteps')
  2325. // var gitUser = 'guest';
  2326. // var gitEmail = 'guest@bbh.org.in';
  2327. // var prompts = [];
  2328. // prompts.push( ()=>{ return cli.prompt(choices['username'], 'git user name').then(gituser => gitUser = gituser) } )
  2329. // prompts.push( ()=>{ return cli.prompt(choices['useremail'], 'git user email').then(gitemail => gitEmail = gitemail) } )
  2330. // console.log('prompting in preinstallsteps')
  2331. // return any(prompts).then(()=>{
  2332. // var steps = [
  2333. // ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  2334. // , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  2335. // ]
  2336. // return any(steps.map(getshelltask)).then(() => {
  2337. // })
  2338. // });
  2339. return Promise.resolve(true)
  2340. })
  2341. return any([any(steps), prompts])
  2342. }
  2343. , installsteps: function () {
  2344. return any([this.installcmd].map(getshelltask))
  2345. }
  2346. , postinstallsteps: function(err, users){
  2347. return this.getuser(null, (err, data)=>{
  2348. // ignore err and proceed with data as guest.
  2349. console.dir(data)
  2350. if(data && data.length === 1 && !shouldPrompt('username', promptkeys, selectedinstance) ) {
  2351. return username = data[0];
  2352. }
  2353. data = data || ['guest']
  2354. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  2355. console.log('prompting in postinstallsteps')
  2356. var username = 'guest';
  2357. var email = 'guest@bbh.org.in';
  2358. var password = '***';
  2359. return any( getInteractionPoints(selectedinstance, promptkeys, { username, password, email}) ).then(()=>{
  2360. if(!data.find(e => e === selectedinstance.username)) {
  2361. var steps = [
  2362. ['git', ['config', '--global', '--add', 'user.name', `${username}`]]
  2363. , ['git', ['config', '--global', '--add', 'user.email', `${email}`]]
  2364. ]
  2365. return any(steps.map(getshelltask)).then(() => {
  2366. })
  2367. }
  2368. else {
  2369. return Promise.resolve(true)
  2370. }
  2371. });
  2372. })
  2373. }
  2374. , install: function () {
  2375. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  2376. }
  2377. , verifyAndInstall : function(){
  2378. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  2379. if(exists) {
  2380. // return any(['git', ['config', '--global', '-l']].map(getshelltask))
  2381. return this.postinstallsteps.bind(this)()
  2382. }
  2383. return this.install();
  2384. });
  2385. }
  2386. , getuser : function(repo, onResult){
  2387. var __onResult = onResult || function(e, data){
  2388. data = data || []
  2389. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  2390. // console.dir(choices)
  2391. return data[0]
  2392. }
  2393. var globalOrLocal = '--global';
  2394. if(repo) globalOrLocal = '--local'
  2395. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(getshelltask)).then((result)=>{
  2396. // not yet configured.
  2397. if(!result.success) return __onResult(result)
  2398. else {
  2399. var users = result.messages[0].trim().split('\n');
  2400. if(users.length === 0 ||
  2401. users.length === 1 && users[0] === 'guest') {
  2402. return __onResult(result)
  2403. }
  2404. else {
  2405. return __onResult(null, Array.from( new Set( users ) ) ); }// PB : TODO == We should probably prompt with all the users available for selection !
  2406. }
  2407. })
  2408. .catch((e)=>{
  2409. console.log(e)
  2410. return __onResult(e)
  2411. })
  2412. }
  2413. }
  2414. ,
  2415. {
  2416. shellcmd: 'node',
  2417. name : 'ndoe',
  2418. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  2419. , installer: 'node-v14.16.0-x64.msi'
  2420. , installcmd: ['MSIEXEC.exe', ['/i'
  2421. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  2422. , 'ACCEPT=YES', '/passive']]
  2423. , install : function() { return any([this.installcmd].map(getshelltask)).then(() => { }) }
  2424. }
  2425. ]
  2426. for(var i=0; i<prerequisites.length; i++) {
  2427. prerequisites[prerequisites[i].name] = prerequisites[i];
  2428. }
  2429. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  2430. function ensureDirectoryExistence(filePath) {
  2431. var dirname = path.dirname(filePath);
  2432. if (fs.existsSync(dirname)) {
  2433. return filePath;
  2434. }
  2435. ensureDirectoryExistence(dirname);
  2436. fs.mkdirSync(dirname);
  2437. return filePath;
  2438. }
  2439. var mainTasks = [];
  2440. function verifyAndInstallPrerequisites() {
  2441. fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
  2442. // PB : TODO include and build from files... using rollup..
  2443. var downloadbatch =
  2444. `::**************************************************************************
  2445. :Download_ <url> <File>
  2446. Powershell.exe ^
  2447. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  2448. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  2449. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  2450. exit /b
  2451. ::**************************************************************************`
  2452. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch)
  2453. var windowselevate =
  2454. `
  2455. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  2456. <script language="vbscript">
  2457. document.title = "elxr control panel"
  2458. self.ResizeTo 200,600
  2459. Sub Window_Onload
  2460. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  2461. End Sub
  2462. Set objShell = CreateObject("WScript.Shell")
  2463. Set objENV = objShell.Environment("Process")
  2464. dim NODE_ENV
  2465. NODE_ENV = objENV("NODE_ENV")
  2466. </script>
  2467. <script language="javascript">
  2468. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  2469. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  2470. // alert(windowselevate.commandLine)
  2471. var args = windowselevate.commandLine.split('"').slice(3);
  2472. // alert(args)
  2473. var processedArgs = { _ : [] }
  2474. var namedArgs = [];
  2475. for(var item in args){
  2476. if(args[item].charAt(0) === '-'){
  2477. namedArgs.push(args[item])
  2478. var split = args[item].split('=');
  2479. processedArgs[split[0].slice(2)] = split[1] || true;
  2480. }
  2481. else processedArgs._.push(args[item]);
  2482. }
  2483. // args = args.forEach(function(item){ })
  2484. // alert('processedArgs._ : ' + processedArgs._);
  2485. // alert(processedArgs.runas);
  2486. // PB : TODO -- Convert all the cli args back to string.
  2487. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  2488. // alert(cargs)
  2489. var shell = new ActiveXObject('shell.application');
  2490. // alert('launching node privilged. ' + processedArgs['nodepath'])
  2491. // shell.ShellExecute('where', 'node', '', '', 10);
  2492. shell.ShellExecute('node', cargs, '', 'runas', 1);
  2493. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  2494. var fso = new ActiveXObject('Scripting.FileSystemObject');
  2495. window.onload = function() {
  2496. document.body.style.backgroundColor = 'black';
  2497. document.body.style.fontFamily = 'arial';
  2498. var log = document.createElement('div');
  2499. log.innerHTML='Please Wait';
  2500. function l(msg){ log.innerHTML+= msg; };
  2501. log.style.color = 'blue';
  2502. log.style.width = '95%';
  2503. log.id = 'log';
  2504. document.body.appendChild(log);
  2505. l('<Br/>Current config : ')
  2506. l('<Br/>NODE_ENV = ' + NODE_ENV)
  2507. l('<Br/>cmd = ' + processedArgs._[0])
  2508. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  2509. l('<Br/><Br/>')
  2510. var timer = function(){
  2511. l('.');
  2512. if(fso.FileExists("run.done")) close();
  2513. else window.setTimeout(timer, 1000);
  2514. };
  2515. window.setTimeout(timer, 3000);
  2516. };
  2517. </script>
  2518. </html>
  2519. `
  2520. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate)
  2521. var downloadtasks = [];
  2522. var installtasks = [];
  2523. prerequisites.forEach(preq => {
  2524. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  2525. if (exists) console.log(`${preq.shellcmd} exists`)
  2526. else {
  2527. console.log(`${preq.shellcmd} is not installed`)
  2528. return preq.preinstallsteps.call(preq).then(() => {
  2529. installtasks.push(preq.install.bind(preq))
  2530. })
  2531. }
  2532. }))
  2533. })
  2534. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  2535. }
  2536. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  2537. return {
  2538. get (){
  2539. return cli.prompt( promptable.choices, promptable.label, promptable.defaultchoice ).then(propValue => {
  2540. var asyncprop = Promise.resolve(propValue)
  2541. if(promptable.interpret){
  2542. asyncprop = promptable.interpret(propValue)
  2543. }
  2544. return asyncprop.then(
  2545. ()=>{
  2546. Object.defineProperty(this, propName, {
  2547. value: propValue,
  2548. writable: true,
  2549. configurable : true,
  2550. enumerable : true
  2551. });
  2552. return propValue
  2553. }
  2554. )
  2555. })
  2556. }
  2557. // , set (propValue){
  2558. // Object.defineProperty(this, propName, {
  2559. // value: propValue,
  2560. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  2561. // configurable : true,
  2562. // enumerable : true
  2563. // })
  2564. // return propValue;
  2565. // }
  2566. , configurable : true
  2567. , enumerable : true
  2568. }
  2569. }
  2570. function acquirelocalinstances(selected){
  2571. // utils.assign is used to cleanup duplicates...
  2572. var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
  2573. return chessinstances
  2574. }
  2575. function findlocalinstances(chessinstances, instanceoptions){
  2576. // We can expect a .elxr at each level.
  2577. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../..' /* instanceNames */].
  2578. earlyreduce( ( value, p, i, a )=>{
  2579. var localinstancesPath = `${instanceroot}/${p}.elxr`;
  2580. if(existsSync( localinstancesPath )) {
  2581. try {
  2582. var chessinstances = acquirelocalinstances( { localinstancesPath } )
  2583. return Object.keys(chessinstances).earlyreduce( ( value, instanceName) => {
  2584. return Object.keys(chessinstances[instanceName]).earlyreduce( (value, instanceType) => {
  2585. if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize( instanceroot) ) {
  2586. instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType])
  2587. return {
  2588. value : chessinstances[instanceName][instanceType]
  2589. , done : true
  2590. };
  2591. }
  2592. })
  2593. })
  2594. }
  2595. catch(e){
  2596. return { }
  2597. }
  2598. }
  2599. else return { }
  2600. }
  2601. )
  2602. }
  2603. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  2604. var selectedinstance = null;
  2605. var chessinstances = { current_run : {} };
  2606. var promptkeys = {
  2607. cmd : processedArgs._[0]
  2608. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  2609. // 'instanceName' : true
  2610. // , 'node_env' : true
  2611. , username : ''
  2612. }
  2613. promptkeys.runchoice = promptkeys.cmd ? 'c' : undefined
  2614. function createChessInsance( cfg ){
  2615. var inst = {};
  2616. var __new = Object.assign({}, __default, cfg)
  2617. inst[cfg.node_env] = __new; return inst;
  2618. }
  2619. var choices = {
  2620. 'instanceName' : []
  2621. , 'reposerver' : []
  2622. , 'instanceType' : []
  2623. , username : ['guest', 'chessdemo', 'demo']
  2624. }
  2625. var getInteractionPoints = function(detectedinstanceoptions, promptkeys, promptsfilter){
  2626. var instances = []
  2627. var reposervers = [];
  2628. var instnaceNames = []
  2629. var instanceTypes = ['development', 'production'];
  2630. Object.keys( chessinstances).forEach(instanceName => {
  2631. if(instanceName === 'current_run') return;
  2632. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  2633. var instance = chessinstances[instanceName][node_env];
  2634. reposervers = reposervers.concat(instance.reposervers)
  2635. if(instance.reposerver) reposervers.push(instance.reposerver)
  2636. instances.push(instance)
  2637. instanceTypes.push(instance.node_env)
  2638. instnaceNames.push(instance.instanceName)
  2639. })
  2640. })
  2641. instances = instances.concat(detectedinstanceoptions)
  2642. if(selectedinstance['instanceName']) instnaceNames.push(selectedinstance['instanceName'])
  2643. if(promptkeys['instanceName']) instnaceNames.push(promptkeys['instanceName'])
  2644. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers'])
  2645. choices['instanceName'] = Array.from( new Set(instnaceNames.concat(choices['instanceName'])) )
  2646. choices['reposerver'] = Array.from( new Set(reposervers.concat(choices['reposerver'])) )
  2647. choices['instanceType'] = Array.from( new Set(instanceTypes.concat(choices['instanceType'])) )
  2648. return __interactive_prompts(selectedinstance, choices, promptsfilter)
  2649. }
  2650. var detection_state = {
  2651. didWeFindInstance : false
  2652. }
  2653. const https = require('https')
  2654. const http = require('http')
  2655. const HTTPAPI = (function(){
  2656. // Singleton
  2657. function HTTPAPI(){}
  2658. // HTTPAPI.create = HTTPAPI; // Returns the one singe instance which is the class itself
  2659. HTTPAPI.post = function(options, jsonpostpayload, resolve, reject){
  2660. var _post = function(options, jsonpostpayload, resolve, reject) {
  2661. console.dir(options)
  2662. console.dir(jsonpostpayload)
  2663. const data = new TextEncoder().encode(
  2664. JSON.stringify(jsonpostpayload)
  2665. )
  2666. options.headers = options.headers || {
  2667. 'Content-Type': 'application/json',
  2668. 'Content-Length': data.length
  2669. }
  2670. if(!options.authenticatepost) options.headers.Authorization = `token ${usertokens[options.username]}`
  2671. // const options = {
  2672. // hostname: 'whatever.com',
  2673. // port: 443,
  2674. // path: '/todos',
  2675. // method: 'POST',
  2676. // headers: {
  2677. // 'Content-Type': 'application/json',
  2678. // 'Content-Length': data.length
  2679. // }
  2680. // }
  2681. var acquirer = getHTTP_S(options)
  2682. const req = acquirer.request(options, res => {
  2683. if (res.statusCode < 200 || res.statusCode >= 300) {
  2684. return reject(new Error('statusCode=' + res.statusCode));
  2685. }
  2686. var body = [];
  2687. res.on('data', function(chunk) {
  2688. body.push(chunk);
  2689. });
  2690. res.on('end', function() {
  2691. try {
  2692. body = JSON.parse(Buffer.concat(body).toString());
  2693. } catch(e) {
  2694. reject(e);
  2695. }
  2696. resolve(body);
  2697. });
  2698. });
  2699. req.on('error', error => {
  2700. console.error(error)
  2701. reject(error)
  2702. })
  2703. req.write(data)
  2704. req.end()
  2705. }
  2706. if(!options.authenticatepost && !usertokens[options.username]) {
  2707. HTTPAPI.authenticate(options, function(tokenresp){
  2708. usertokens[options.username] = tokenresp.sha1
  2709. _post(options, jsonpostpayload, resolve, reject)
  2710. },
  2711. function(err){ throw err}
  2712. )
  2713. }
  2714. else _post(options, jsonpostpayload, resolve, reject)
  2715. }
  2716. var usertokens = {}
  2717. HTTPAPI.authenticate = function(options, resolve, reject){
  2718. options.headers = options.headers || { 'Content-Type': 'application/json' }
  2719. if(!usertokens[options.username]) {
  2720. // Authenticate and acquire token.
  2721. // https://git.bbh/api/v1/users/<username>/tokens
  2722. // curl -XPOST -H "Content-Type: application/json" -k -d '{"name":"demo"}' -u demo:demo123 http://git.bbh/api/v1/users/demo/tokens
  2723. var _options = Object.assign({}, options)
  2724. // _options.username = 'demo'
  2725. // _options.password = 'demo123'
  2726. _options.method = 'POST'
  2727. _options.headers.Authorization = `Basic ${Buffer.from(`${_options.username}:${_options.password}`).toString('base64')}`
  2728. _options.path = `/api/v1/users/${_options.username}/tokens`
  2729. _options.authenticatepost = true
  2730. var postoptions = { name : _options.username }
  2731. delete _options.username
  2732. delete _options.password
  2733. HTTPAPI.post( _options, postoptions, function(tokenresp){
  2734. // tokenresp = JSON.parse(tokenresp)
  2735. usertokens[options.username] = tokenresp.sha1
  2736. resolve(tokenresp)
  2737. },
  2738. function(err){ reject(err) }
  2739. )
  2740. }
  2741. else resolve(tokenresp.sha1)
  2742. }
  2743. HTTPAPI.get = function(options, resolve, reject){
  2744. options.headers = options.headers || { 'Content-Type': 'application/json' }
  2745. if(!usertokens[options.username]) {
  2746. HTTPAPI.authenticate(options, function(tokenresp){
  2747. usertokens[options.username] = tokenresp.sha1
  2748. _get(options, resolve, reject)
  2749. },
  2750. function(err){ throw err}
  2751. )
  2752. }
  2753. else _get(options, resolve, reject)
  2754. var _get = function() {
  2755. options.headers.Authorization = `token ${usertokens[options.username]}`
  2756. // const options = {
  2757. // hostname: 'whatever.com',
  2758. // port: 443,
  2759. // path: '/todos',
  2760. // method: 'POST',
  2761. // headers: {
  2762. // 'Content-Type': 'application/json',
  2763. // 'Content-Length': data.length
  2764. // }
  2765. // }
  2766. var acquirer = getHTTP_S(options)
  2767. const req = acquirer.request(options, res => {
  2768. if (res.statusCode < 200 || res.statusCode >= 300) {
  2769. return reject(new Error('statusCode=' + res.statusCode));
  2770. }
  2771. var body = [];
  2772. res.setEncoding('utf8');
  2773. res.on('data', function(chunk) {
  2774. body.push(chunk);
  2775. });
  2776. res.on('end', function() {
  2777. try {
  2778. body = JSON.parse(Buffer.concat(body).toString());
  2779. } catch(e) {
  2780. reject(e);
  2781. }
  2782. resolve(body);
  2783. });
  2784. });
  2785. req.on('error', error => {
  2786. console.error(error)
  2787. reject(error)
  2788. })
  2789. req.end()
  2790. }
  2791. }
  2792. return HTTPAPI
  2793. })();
  2794. var getHTTP_S = function(options){ return options.protocol.startsWith('https') ? https : http; }
  2795. const GITEA = (function(){
  2796. function GITEA(){}
  2797. GITEA.repository = {
  2798. fork( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  2799. // forkoptions = { owner : httpoptions.username, repo : {{reoptoFork}} }
  2800. // giteaoptions = {
  2801. // organization string
  2802. // --- organization name, if forking into an organization
  2803. // }
  2804. // http://try.gitea.io/api/v1/repos/{owner}/{repo}/forks
  2805. httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}/forks`
  2806. httpoptions.method = 'POST'
  2807. return HTTPAPI.post(httpoptions, giteaoptions, resolve || function(){}, reject || function(){} )
  2808. }
  2809. , updateattributes( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  2810. httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}`
  2811. httpoptions.method = 'PATCH'
  2812. return HTTPAPI.post(httpoptions, giteaoptions, resolve || function(){}, reject || function(){} )
  2813. }
  2814. }
  2815. return GITEA
  2816. })();
  2817. function createInstance(selectedinstance) {
  2818. // http://try.gitea.io/api/v1/org/{org}/repos
  2819. console.dir(selectedinstance)
  2820. var server = new URL(selectedinstance.reposerver);
  2821. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  2822. , username : selectedinstance.username, password : selectedinstance.password
  2823. }
  2824. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  2825. , { repo : `chess-config`, owner : 'chess' }, {}, function( repository ){
  2826. return GITEA.repository.updateattributes( {
  2827. hostname : server.host, protocol : server.protocol
  2828. , username : selectedinstance.username, password : selectedinstance.password
  2829. }
  2830. , { repo : `chess-config`, owner : selectedinstance.username }
  2831. , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  2832. )
  2833. }
  2834. )
  2835. // GITEA.repository.updateattributes( {
  2836. // hostname : server.host, protocol : server.protocol
  2837. // , username : selectedinstance.username, password : selectedinstance.password
  2838. // }
  2839. // , { repo : `chess-config`, owner : selectedinstance.username }
  2840. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  2841. // )
  2842. // return selectedinstance
  2843. }
  2844. acquireElevationState().then(() => {
  2845. var skipprerequisites = false;
  2846. function initinstances(selected_overrides) {
  2847. var root = selected_overrides.root // We should always have this coz we are running at some place which is fixed by detectinstances.
  2848. var instanceName = selected_overrides.instanceName
  2849. || clioverrides.instanceName
  2850. // || processedArgs._[1]
  2851. || chessinstances.current_run.instanceName
  2852. var node_env = selected_overrides.node_env
  2853. || clioverrides.node_env
  2854. // || processedArgs.node_env
  2855. || chessinstances.current_run.node_env
  2856. var reposerver = selected_overrides.reposerver
  2857. || clioverrides.reposerver
  2858. // || processedArgs.node_env
  2859. || chessinstances.current_run.reposerver
  2860. if(!instanceName) {
  2861. promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  2862. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  2863. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  2864. }
  2865. if(!node_env) {
  2866. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  2867. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  2868. }
  2869. if(!reposerver) {
  2870. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  2871. }
  2872. chessinstances[instanceName] = chessinstances[instanceName] || createChessInsance( {
  2873. instanceName, node_env, root : selected_overrides.root, reposerver : promptkeys['reposerver'] } );
  2874. chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root }
  2875. if(path.normalize(selected_overrides.root) !== path.normalize(chessinstances[instanceName][node_env].root)) {
  2876. throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selected_overrides.root
  2877. }
  2878. // Override sequence.
  2879. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  2880. selectedinstance = utils.assign(
  2881. chessinstances[instanceName][node_env]
  2882. , clioverrides
  2883. , selected_overrides
  2884. // , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
  2885. );
  2886. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  2887. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  2888. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  2889. // // Brand New.
  2890. // selectedinstance = Object.assign( __default, selectedinstance )
  2891. // }
  2892. if(!selectedinstance.repos[0].repo) {
  2893. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  2894. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  2895. }
  2896. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  2897. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  2898. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  2899. }
  2900. // Config from server always override merges into selection except for the current selection.
  2901. // PB : TODO -- utils.assign Array merges are non-distinct...
  2902. chessinstances[instanceName][node_env] = selectedinstance;
  2903. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  2904. cacheWriteInstanceConfig(chessinstances)
  2905. // PB : TODO -- We should probably write the new server config also...
  2906. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  2907. return chessinstances
  2908. }
  2909. var skipprereqs = {}
  2910. var maintask = () => {
  2911. // Default cmd to run !
  2912. processedArgs._[0] === processedArgs._[0] || 'pull';
  2913. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  2914. if(!noprerequisites[processedArgs._[0]]
  2915. && !skipprereqs[processedArgs._[0]]
  2916. ) {
  2917. return prerequisites.git.verifyAndInstall().then(()=>{
  2918. var e = { message : 'verifyAndInstall', success : true}
  2919. var inittasks = []
  2920. if(!detection_state.didWeFindInstance) {
  2921. inittasks.push(createInstance(selectedinstance).then(() => { preworkerconfig(); return elxrworker(true) }))
  2922. }
  2923. else {
  2924. inittasks.push(acquireConfig(selectedinstance).catch((err) => {
  2925. e = err;
  2926. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  2927. console.error(err)
  2928. }).then(() => { preworkerconfig(); return elxrworker(true) })
  2929. // .finally(()=>{
  2930. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  2931. // if(!e.success) fs.writeFileSync('run.done', 'error');
  2932. // // return process.exit()
  2933. // }))
  2934. )
  2935. }
  2936. return any(inittasks)
  2937. })
  2938. }
  2939. else {
  2940. console.log('cmd has no preqs or has been configured to skip preqs')
  2941. preworkerconfig()
  2942. return elxrworker()
  2943. }
  2944. }
  2945. const retaincount = 2
  2946. var min = runtimestamp;
  2947. var collect = []
  2948. if(reconfirmcmds[processedArgs.label || processedArgs._[0]]) {
  2949. reconfirm = getReconfirmAll()
  2950. }
  2951. return detectinstances().then((detectedinstanceoptions)=>{
  2952. detectedinstanceoptions.splice(0,0, __default)
  2953. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  2954. selectedinstance = utils.assign( ...detectedinstanceoptions.slice(-2), promptkeys )
  2955. // promptkeys = utils.assign(promptkeys, clioverrides)
  2956. console.dir(selectedinstance)
  2957. try {
  2958. chessinstances = acquirelocalinstances(selectedinstance);
  2959. findlocalinstances(chessinstances, detectedinstanceoptions)
  2960. initinstances(selectedinstance) // use the local instances for defaults if at all possible.
  2961. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  2962. var inst = initinstances(selectedinstance)
  2963. detection_state.didWeFindInstance = true;
  2964. return inst;
  2965. })
  2966. }
  2967. catch (e) {
  2968. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  2969. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  2970. return initinstances(selectedinstance)
  2971. })
  2972. // if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  2973. // // Weve not been told what to do.
  2974. // todo = todo.then(() => { return acquireChoices(selectedinstance) })
  2975. // }
  2976. todo = todo.then(() => {
  2977. try {
  2978. chessinstances = acquirelocalinstances(selectedinstance)
  2979. findlocalinstances(chessinstances, detectedinstanceoptions)
  2980. detectedinstanceoptions.splice(0,0, __default)
  2981. initinstances(selectedinstance)
  2982. detection_state.didWeFindInstance = true;
  2983. }
  2984. catch (e) {
  2985. // console.error(e)
  2986. console.log('No local instances config found in current root = ' + selectedinstance.root);
  2987. console.log('A config will be createed with the instance and environment chosen...')
  2988. // return (async ()=>{return await __default.reposerver})().then(()=>{
  2989. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  2990. // return selectedinstance = Object.assign(__default, selectedinstance);
  2991. // })
  2992. detection_state.didWeFindInstance = false;
  2993. return selectedinstance
  2994. }
  2995. })
  2996. }
  2997. return todo
  2998. })
  2999. .then(()=>{
  3000. if(noprerequisites[processedArgs._[0]]
  3001. || skipprereqs[processedArgs._[0]]
  3002. ) {
  3003. return elxrworker()
  3004. }
  3005. if(!__isElevated) {
  3006. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`)
  3007. // collect garbage
  3008. return dirs( (dir)=>{
  3009. var matches = /run-(.*)/gm.exec(dir.name)
  3010. if(matches) {
  3011. if(+(matches[1]) < min) {
  3012. min = matches[1]
  3013. collect.splice( 0, 0, matches[1] )
  3014. }
  3015. else collect.push(matches[1])
  3016. }
  3017. }, `${selectedinstance.root}/.elxr` ).then(()=>{
  3018. // delete garbage
  3019. if(collect.length > retaincount) {
  3020. var asyncs = [];
  3021. while((collect.length - asyncs.length) > retaincount) {
  3022. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  3023. }
  3024. return Promise.all(asyncs)
  3025. }
  3026. else return true
  3027. })
  3028. }
  3029. else return true;
  3030. })
  3031. .then(()=>{
  3032. // PB : TODO -- Keep only the last n runs...
  3033. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  3034. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
  3035. if (!skipprerequisites && !__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
  3036. mainTasks.push(maintask)
  3037. return any(mainTasks);
  3038. })
  3039. })
  3040. // detect if alread installed -> Take no action.
  3041. // download if no installer avalable -> next()
  3042. // install
  3043. function chackandinstall(items) {
  3044. var tasks = []
  3045. items.forEach(item => {
  3046. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  3047. })
  3048. return Promise.all(tasks).then(existances => {
  3049. existances.forEach((exists, i) => {
  3050. if (!exists) {
  3051. return downloadandinstall([items[i]])
  3052. }
  3053. })
  3054. })
  3055. }
  3056. function downloadandinstall(items) {
  3057. var tasks = []
  3058. items.forEach(item => {
  3059. tasks.push(getTaskDownload(item))
  3060. })
  3061. return Promise.all(tasks)
  3062. }
  3063. // Sample instances config.
  3064. // var instances = {
  3065. // "elixir": {
  3066. // "production": {
  3067. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  3068. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  3069. // , "exludeMergeRepos": {
  3070. // "elixir-config-development": true, "elixir-config-test": true
  3071. // , "elixir-config-production": true, "elixir-data": true
  3072. // }
  3073. // , "instanceName": "elixir", "node_env": "production"
  3074. // }
  3075. // },
  3076. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  3077. // }
  3078. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...