Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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