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

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