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.

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