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

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