Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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