You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 151KB

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