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

index.js 93KB

3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
4 yıl önce
4 yıl önce
3 yıl önce
3 yıl önce
5 yıl önce
6 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
6 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
4 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
5 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
5 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
6 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
3 yıl önce
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525
  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 BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  12. const runtimestamp = (new Date()).getTime();
  13. function getVersion() { return BUILD_VERSION; }
  14. console.log(getVersion())
  15. // 'use strict';
  16. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  17. // PB : TODO --
  18. // runas bypass non elevated tasks when we request privelege
  19. // runas message is always error needs to be fixed.
  20. // runas wait needs to be parallelized.
  21. // suppress elevation check error messages
  22. // support runas lauched directly from shell.
  23. // pass in environment in hta to shellexecute.
  24. const { existsSync } = require('fs');
  25. const fs = require('fs')
  26. const cliargs = utils.cliargs;
  27. const processedArgs = cliargs(process.argv.slice(2));
  28. console.dir(processedArgs)
  29. // PB : TODO -- defaults for valuless arguments if passed.
  30. // Object.keys(processedArgs).forEach(a=>{
  31. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  32. // }
  33. // })
  34. var globSync = require('glob').sync;
  35. var ENV = Object.assign({}, process.env); // Shallow clone it.
  36. const { readdir } = require("fs").promises
  37. // Directory shallow walk and do perform on each dir.
  38. const dirs = async (perform, path) => {
  39. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  40. if (dir.isDirectory()) perform(dir)
  41. }
  42. }
  43. var getShellTask = (command, args, options) => {
  44. options = options || {}
  45. return () => {
  46. var p = nodeShellExec.apply(null, [command, args, Object.assign({
  47. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  48. }, options)
  49. ])
  50. if (options.ignorefailures) {
  51. return p.catch(e => {
  52. // Ignore. Not a major error.
  53. })
  54. }
  55. else return p;
  56. }
  57. }
  58. var callsheltask = (args) => { return () => { return nodeShellExec.apply(null, args) } }
  59. var callgitbashtask = (args) => { return () => {
  60. return nodeShellExec( `"${gitbash}"`, ['-c', `"${args[0]} ${args[1].join(' ')}"`], args[2]) }
  61. }
  62. var getTaskCheckExists = (command, options) => {
  63. options = options || {}
  64. return () => {
  65. var p = nodeShellExec.apply(null, ['where', [command]])
  66. if (options.ignorefailures) {
  67. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  68. return false;
  69. })
  70. }
  71. else return p.then(() => { return true });
  72. }
  73. }
  74. var getTaskWithElevation = function(tasdef){
  75. return ()=>{
  76. if (__isElevated) {
  77. return tasdef.elevatedpulltasks().then(()=>{
  78. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  79. fs.writeFileSync('run.done', 'success')
  80. }).catch(e=>{
  81. fs.writeFileSync('run.done', 'failure')
  82. });
  83. }
  84. else {
  85. // PB : TODO -- Rename op['runas'] to 'elevate'
  86. var __runasresult = null;
  87. return op['runas']().then((r) => { return __runasresult = r; })
  88. .catch((e) => {
  89. console.error(e)
  90. })
  91. .finally(() => {
  92. if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done')
  93. if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
  94. })
  95. }
  96. }
  97. }
  98. var getTaskWithoutElevation = function(tasdef){
  99. return ()=>{
  100. if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  101. else Promise.resolve(true)
  102. }
  103. }
  104. var gitops = {
  105. getdiscoverbranchcmd : function(repo){
  106. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  107. var cmd = [gitbash
  108. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  109. , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo + ' ' + parameters.join(' ') }]
  110. return cmd
  111. }
  112. }
  113. var getPullCmd = (repo, branch) => {
  114. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  115. // console.log(useGitPull)
  116. // var pullCmd = [gitInstallDir
  117. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  118. // , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo }]
  119. if(branch) {
  120. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  121. var pullCmd = [ gitbash
  122. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  123. , { cwd: instanceroot + '/' + repo, title : 'pull all origins for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  124. }
  125. else {
  126. console.warn('No branch was specified detecting from working client.')
  127. // First check if working client exits.
  128. // if (existsSync(instanceroot + '/' + repo)) {
  129. var pullCmd = gitops.getdiscoverbranchcmd(repo)
  130. // }
  131. // else performpull
  132. }
  133. // var pullCmd = ['pullall', [], { cwd : repo }]
  134. if (useGitPull) pullCmd = ['git', ['pull'], {
  135. inherit: true, shell: true,
  136. cwd: instanceroot + '/' + repo
  137. // , env: process.env
  138. , runas: processedArgs.runas
  139. , title: `git pull ${repo}`
  140. }]
  141. return pullCmd
  142. }
  143. var performPull = (repo, branch) => {
  144. // PB : TODO -- Handle no branch passed in case.
  145. // if(!branch) { throw 'No branch specified' }
  146. if (existsSync(instanceroot + '/' + repo)) {
  147. var branchprint = branch ? ' branch :' + branch : '';
  148. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  149. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  150. if (__isElevated) {
  151. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  152. }
  153. else statuslog.statuslog(null, repo)
  154. return true;
  155. })
  156. .catch((e) => {
  157. e.repo = repo;
  158. if (__isElevated) {
  159. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  160. }
  161. else statuslog.statuslog(e); console.error(e)
  162. })
  163. }
  164. else {
  165. console.log('cloning ' + repo)
  166. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  167. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'],
  168. {
  169. inherit: true, shell: true,
  170. env: process.env
  171. , cwd : instanceroot
  172. , runas: processedArgs.runas
  173. }).catch((e) => {
  174. throw e;
  175. }).then(() => {
  176. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  177. {
  178. inherit: true, shell: true,
  179. env: process.env
  180. , cwd: instanceroot + '/' + repo
  181. , runas: processedArgs.runas
  182. , title: `git core.symlinks --replace-all true for ${selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'}`
  183. })
  184. .then(() => {
  185. if (__isElevated) {
  186. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  187. }
  188. else statuslog.statuslog(null, repo)
  189. })
  190. .catch((e) => {
  191. e.repo = repo;
  192. if (__isElevated) {
  193. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  194. }
  195. else statuslog.statuslog(e);
  196. })
  197. })
  198. .catch(e => {
  199. e.repo = repo;
  200. if (__isElevated) {
  201. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  202. }
  203. else statuslog.statuslog(e);
  204. })
  205. }
  206. }
  207. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  208. // -- Currently workaround is to always run from a non-elevated shell.
  209. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  210. var acquireElevationState = () => {
  211. if (__isElevated === null) {
  212. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  213. inherit: true
  214. // , shell: true
  215. , stdio: 'ignore'
  216. , env: process.env
  217. , title: `check privileged execution mode using "fsutil dirty query C:"`
  218. }).then((exitcode) => {
  219. console.log('Elevated')
  220. __isElevated = true;
  221. return true;
  222. }).catch(() => {
  223. __isElevated = false;
  224. console.log('Not Elevated');
  225. return false;
  226. });
  227. }
  228. else return Promise.resolve(__isElevated);
  229. }
  230. var repomanifest = null;
  231. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current gittea username
  232. var defaultRepoOwner = 'chess';
  233. var elevatedRunasRepos = null
  234. var gitRepos = null
  235. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  236. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  237. var dbForLabel = function (label) {
  238. var dbsForLabel = {
  239. devmysql: 'mysql'
  240. , development: 'mssql'
  241. , production: 'mssql'
  242. }
  243. return dbsForLabel[label] || 'mysql'
  244. }
  245. // SAM : TODO Use nodeshellexec where to detect git installation dir
  246. var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe"
  247. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  248. // Relevant git repos
  249. // var repomanifest = require('../'+repomanifest.instanceName+'-config-'+ nodeenv +'/repo-manifest')()
  250. var exludeMergeRepos = [];
  251. var useGitPull = processedArgs.useGitPull || false;
  252. var configPromise = null
  253. // elxr cli operations
  254. var op = {
  255. 'h': () => { console.log(elxr.help()); return '-h' }
  256. , 'clean' : () => {
  257. // delete all node_module folders and links.
  258. var tasklist = [];
  259. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot )
  260. return Promise.all(tasklist)
  261. }
  262. , 'undefined': () => { return op.h(); }
  263. , 'reset': () => {
  264. // Reset NPM packages semver so major versions can be updated.
  265. const fs = require('fs')
  266. const wipeDependencies = (__package) => {
  267. const file = fs.readFileSync(__package + '/package.json')
  268. const content = JSON.parse(file)
  269. for (var devDep in content.devDependencies) {
  270. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  271. content.devDependencies[devDep] = '*';
  272. }
  273. }
  274. for (var dep in content.dependencies) {
  275. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  276. content.dependencies[dep] = '*';
  277. }
  278. }
  279. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  280. }
  281. var repos = ['client'];
  282. // repos = gitRepos;
  283. repos.forEach(wipeDependencies)
  284. // if (require.main === module) {
  285. // } else {
  286. // module.exports = wipeDependencies
  287. // }
  288. }
  289. , 'upgrade': () => {
  290. console.log('upgrade.......')
  291. var tasks = [
  292. () => {
  293. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  294. inherit: true, shell: true
  295. , env: process.env
  296. }).catch((e) => { console.error(e) })
  297. p.position = 1;
  298. console.log('One')
  299. return p;
  300. }
  301. , () => {
  302. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  303. inherit: true, shell: true
  304. , env: process.env
  305. }).catch((e) => { console.error(e) })
  306. p.position = 2;
  307. console.log('Two')
  308. return p;
  309. }
  310. , () => {
  311. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  312. inherit: true, shell: true
  313. , env: process.env
  314. }).catch((e) => { console.error(e) })
  315. p.position = 3;
  316. console.log('Three')
  317. return p;
  318. }
  319. , () => {
  320. var p = nodeShellExec('n', ['latest'], {
  321. inherit: true, shell: true
  322. , env: process.env
  323. }).catch((e) => { console.error(e) })
  324. p.position = 4;
  325. console.log('Four')
  326. return p;
  327. }
  328. ]
  329. any(tasks)
  330. console.log('.......done')
  331. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  332. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  333. console.info('Uninstalling existing ember globally');
  334. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  335. stdio: ['pipe', process.stdout, process.stderr],
  336. inherit: true,
  337. shell: true,
  338. cwd: path.dirname(__dirname),
  339. env: env
  340. })
  341. step1.on('close', () => {
  342. console.info('Installing ember globally');
  343. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  344. stdio: ['pipe', process.stdout, process.stderr],
  345. inherit: true,
  346. shell: true,
  347. cwd: path.dirname(__dirname),
  348. env: env
  349. })
  350. step2.on('close', () => {
  351. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  352. stdio: ['pipe', process.stdout, process.stderr],
  353. inherit: true,
  354. shell: true,
  355. cwd: path.dirname(__dirname),
  356. env: env
  357. })
  358. })
  359. })
  360. }
  361. , 'runas': () => {
  362. if(processedArgs.skipelevated) return Promise.resolve({ skipped : true });
  363. console.log('Testing Elevation')
  364. if (__isElevated) {
  365. try {
  366. op[processedArgs.label || processedArgs._[0] || 'h']()
  367. }
  368. catch (e) {
  369. console.error('Error Invalid command : ' + e)
  370. fs.writeFileSync('run.done', 'error')
  371. }
  372. finally {
  373. }
  374. }
  375. else {
  376. console.log('Requesting Elevated Privileges');
  377. // Wait for the runas to complete before we read it.
  378. try {
  379. fs.unlinkSync('run.done')
  380. fs.unlinkSync('run.log')
  381. }
  382. catch (e) { } //Ignore
  383. // Find node path to send to hta.
  384. return nodeShellExec('where', ['node']).then(r => {
  385. var namedArgs = [];
  386. console.log('result : ' + JSON.stringify(r))
  387. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; })
  388. // PB : TODO -- Convert all the cli args back to string.
  389. var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  390. args.push('--nodepath=' + r[r.length - 1])
  391. if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
  392. if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
  393. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  394. , {
  395. inherit: true
  396. , shell: true
  397. , env: ENV
  398. , runas: 'self'
  399. , title: `runas`
  400. }
  401. ).then(() => {
  402. // runas returned.
  403. try {
  404. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  405. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  406. runaslog.forEach((logEntry) => {
  407. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry)
  408. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  409. })
  410. }
  411. catch (e) {
  412. // We must have a runas log
  413. statuslog.statuslog(e)
  414. console.error('Run log error probably was not created by runas : ' + e)
  415. }
  416. })
  417. .catch(err => console.error('Elevation failed : ' + err));
  418. })
  419. }
  420. }
  421. , 'push': () => {
  422. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  423. // init remote bare from local
  424. // pushandinitremotebare
  425. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  426. // connect to repo server -- net use 172.16.0.27
  427. // cd 172.16.0.27/repos/
  428. // mkdir repo.git
  429. // cd repo.git
  430. // git init --bare
  431. // cd localrepo
  432. // git remote rename origin githubclone
  433. // git remote add origin //172.16.0.27/repos/repo.git
  434. // git push origin master
  435. var repo = processedArgs._[1];
  436. var sequentialTaskShellCommands = [];
  437. if (!existsSync(`Z:/${repo}.git`)) {
  438. sequentialTaskShellCommands = [
  439. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  440. // inherit : true, shell: true
  441. // , env: process.env
  442. // }]
  443. ['pwd', { cwd: 'Z:', inherit: true }]
  444. , ['mkdir', [`${repo}.git`], {
  445. cwd: `Z:`
  446. , inherit: true, shell: true
  447. , env: process.env
  448. }]
  449. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  450. , ['git', ['init', '--bare'], {
  451. cwd: `Z:/${repo}.git`
  452. , inherit: true, shell: true
  453. , env: process.env
  454. }]
  455. // PB : TODO -- Do this conditionally only...
  456. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  457. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  458. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  459. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  460. // PB : TODO -- If threre is a gitbubclone origin
  461. // Set the master to pull from the local repo.
  462. ]
  463. if (!existsSync(`Z:`)) {
  464. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  465. inherit: true, shell: true
  466. , env: process.env
  467. }])
  468. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  469. // throw 'done'
  470. }
  471. }
  472. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }])
  473. // console.dir(sequentialTaskShellCommands);
  474. var tasks = [];
  475. sequentialTaskShellCommands.forEach(shellcmd => {
  476. // console.log(shellcmd)
  477. tasks.push(() => {
  478. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
  479. return p;
  480. })
  481. })
  482. any(tasks);
  483. }
  484. , 'is-git-repo': (dir) => {
  485. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  486. }
  487. // git remote equivalents...
  488. // git branch --set-upstream-to=elixir-unc/master master
  489. // git push --set-upstream elixir-unc branch..
  490. , 'remote': (args) => {
  491. // Subcommands!
  492. if(!processedArgs.v) return false;
  493. var serial_perform = (repo) => {
  494. var options = { cwd: instanceroot + '/' + repo }
  495. return [
  496. ['git', ['remote', '-v'], options]
  497. ]
  498. }
  499. var x = (args) => {
  500. var tasq = () => {
  501. // console.log(args)
  502. return nodeShellExec.apply(null, args).catch(e => {
  503. // We continue on failure.
  504. console.error(tasq.toString())
  505. })
  506. }
  507. tasq.toString = function(){
  508. return JSON.stringify(args)
  509. }
  510. return tasq;
  511. }
  512. var perform = (dir) => {
  513. return any(serial_perform(dir.name).map(x))
  514. }
  515. dirs(perform)
  516. }
  517. , 'remote set-url': (args) => {
  518. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  519. var __args = {
  520. remotename : args.remotename || processedArgs._[2]
  521. , url : args.url || processedArgs._[3]
  522. }
  523. // pushable doesn't mean the remote doesn't support being pushed to.
  524. // 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.
  525. // PB : TODO -- change this to enablepushing.
  526. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  527. var pushable = processedArgs.pushable || false;
  528. remotename = __args.remotename
  529. url = __args.url
  530. var serial_perform_git_seturl = (repo) => {
  531. var options = { cwd: instanceroot + '/' + repo }
  532. // console.log(repo)
  533. if (pushable) {
  534. return [
  535. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  536. , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  537. ]
  538. }
  539. else {
  540. return [
  541. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  542. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  543. ]
  544. }
  545. }
  546. var x = (args) => {
  547. var tasq = () => {
  548. // console.log(args)
  549. return nodeShellExec.apply(null, args).catch(e => {
  550. // We continue on failure.
  551. console.error(tasq.toString())
  552. })
  553. }
  554. tasq.toString = function(){
  555. return JSON.stringify(args)
  556. }
  557. return tasq;
  558. }
  559. var perform_git_seturl = (dir) => {
  560. op['is-git-repo'](dir).then((logEntry) => {
  561. return any(serial_perform_git_seturl(dir.name).map(x))
  562. }).catch((e) => {
  563. // console.log('Failed : ' + dir.name)
  564. })
  565. }
  566. dirs(perform_git_seturl)
  567. }
  568. , 'add': (remotename, url, branch) => {
  569. var pushable = processedArgs.pushable || false;
  570. remotename = remotename || processedArgs._[1]
  571. url = url || processedArgs._[2]
  572. branch = branch || processedArgs._[3]
  573. var serial_perform_git_add = (repo) => {
  574. var options = { cwd: instanceroot + '/' + repo }
  575. // console.log(repo)
  576. if (pushable) {
  577. return [
  578. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  579. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  580. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  581. ]
  582. }
  583. else {
  584. return [
  585. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  586. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  587. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  588. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  589. ]
  590. }
  591. }
  592. var x = (args) => {
  593. return () => {
  594. // console.log(args)
  595. return nodeShellExec.apply(null, args)
  596. }
  597. // return Promise.resolve(true)
  598. }
  599. var perform_git_add = (dir) => {
  600. op['is-git-repo'](dir).then((logEntry) => {
  601. // console.log(code)
  602. if (logEntry.success) {
  603. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  604. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  605. })
  606. .catch((e) => {
  607. any(serial_perform_git_add(dir.name).map(x))
  608. })
  609. }
  610. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  611. }).catch((e) => {
  612. // console.log('Failed : ' + dir.name)
  613. })
  614. }
  615. const { readdir } = require("fs").promises
  616. dirs(perform_git_add)
  617. }
  618. , 'remote remove': (args) => {
  619. var __args = {
  620. remotename : args.remotename|| processedArgs._[2]
  621. }
  622. var remotename = __args.remotename
  623. var serial_perform_git_remove = (repo) => {
  624. var options = { cwd: instanceroot + '/' + repo }
  625. // console.log(repo)
  626. return [
  627. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  628. ]
  629. }
  630. var x = (args) => {
  631. return () => {
  632. // console.log(args)
  633. return nodeShellExec.apply(null, args)
  634. }
  635. // return Promise.resolve(true)
  636. }
  637. var perform_git_remove = (dir) => {
  638. op['is-git-repo'](dir).then((logEntry) => {
  639. // console.log(code)
  640. if (logEntry.success) {
  641. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  642. any(serial_perform_git_remove(dir.name).map(x))
  643. })
  644. .catch((e) => {
  645. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`)
  646. })
  647. }
  648. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  649. }).catch((e) => {
  650. // console.log('Failed : ' + dir.name)
  651. })
  652. }
  653. const { readdir } = require("fs").promises
  654. dirs(perform_git_remove)
  655. }
  656. , 'init-gitea': (user) => {
  657. user = user || processedArgs._[1]
  658. if (!user) throw 'User name required'
  659. var serial_perform_init_gitea = (repo) => {
  660. var options = { cwd: instanceroot + '/' + repo }
  661. // console.log(repo)
  662. return [
  663. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  664. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  665. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  666. ]
  667. }
  668. var x = (args) => {
  669. return () => {
  670. // console.log(args)
  671. return nodeShellExec.apply(null, args)
  672. }
  673. // return Promise.resolve(true)
  674. }
  675. var perform_init_gitea = (dir) => {
  676. op['is-git-repo'](dir).then((logEntry) => {
  677. // console.log(code)
  678. if (logEntry.success) {
  679. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  680. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  681. })
  682. .catch((e) => {
  683. any(serial_perform_init_gitea(dir.name).map(x))
  684. })
  685. }
  686. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  687. }).catch((e) => {
  688. // console.log('Failed : ' + dir.name)
  689. })
  690. }
  691. const { readdir } = require("fs").promises
  692. dirs(perform_init_gitea)
  693. }
  694. , 'syncmaster': (label) => {
  695. // Usage :
  696. // elxr pull -- Defaults to run config
  697. var env = Object.assign({}, process.env); // Shallow clone it.
  698. // console.dir(env)
  699. console.log('Running exlr pull : ' + path.dirname(__dirname))
  700. if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'))
  701. if (__isElevated) {
  702. return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
  703. fs.writeFileSync('run.done', 'success')
  704. }).catch(() => {
  705. fs.writeFileSync('run.done', 'error')
  706. })
  707. }
  708. else return op['runas']()
  709. }
  710. , 'repo-relocate' : function(args){
  711. // relocate a subfolder in source repo to same subfolder in target repo with history.
  712. var args = args || {
  713. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  714. , folder : processedArgs._[3] || 'server'
  715. , sourcerepo : processedArgs._[2] || 'client'
  716. , targetrepo : processedArgs._[1] || 'elixir-server'
  717. }
  718. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  719. // , stdio: ['pipe', process.stdout, process.stderr]
  720. , inherit: true,
  721. shell: true,
  722. env: process.env
  723. , runas: processedArgs.runas
  724. }
  725. return op['repo-split'](args).then(()=>{
  726. return op['repo-merge'](args).then(()=>{
  727. // cleanup folder from source.
  728. var cmdseq = [
  729. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  730. // commits have to intentional...
  731. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  732. ]
  733. return any(cmdseq.map(callsheltask))
  734. })
  735. }).catch(e=>{console.error(e)})
  736. }
  737. , 'repo-split' : function(args) {
  738. // https://gist.github.com/smdabdoub/17065c348289158277b5
  739. /**
  740. * Eg : folder, remotebase, sourcerepo, targetrepo
  741. * args.folder = 'server'
  742. * args.remotebase = 'https://git.bbh/chess/'
  743. * args.sourcerepo = 'client'
  744. * args.targetrepo = 'elixir-server'
  745. */
  746. var args = args || {
  747. folder : 'server'
  748. , remotebase : 'http://git.bbh/chess/'
  749. , sourcerepo : 'client'
  750. , targetrepo : 'elixir-server'
  751. }
  752. var options = { cwd: `${instanceroot}/relocate`
  753. // , stdio: ['pipe', process.stdout, process.stderr]
  754. , inherit: true,
  755. shell: true,
  756. env: process.env
  757. , runas: processedArgs.runas
  758. }
  759. var cmdseq = [
  760. // create a temporary working dir in current folder where we started execution.
  761. ['mkdir', [ '-p', 'relocate']]
  762. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  763. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  764. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  765. ]
  766. return any(cmdseq.map(callsheltask)).then(() => {
  767. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  768. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  769. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  770. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  771. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  772. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  773. // subtree split and filter-branch are options. We currently use repo-filter.
  774. return op['filter-repo'](args)
  775. }).catch(e=>{console.error(e); throw 'failed'})
  776. }
  777. , 'repo-merge' : function(args) {
  778. // Merge source repo into target repo
  779. var args = args || {
  780. folder : 'server'
  781. , remotebase : 'http://git.bbh/chess/'
  782. , sourcerepo : 'client'
  783. , targetrepo : 'elixir-server'
  784. }
  785. var sourcerepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  786. // , stdio: ['pipe', process.stdout, process.stderr]
  787. , inherit: true,
  788. shell: true,
  789. env: process.env
  790. , runas: processedArgs.runas
  791. }
  792. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  793. // , stdio: ['pipe', process.stdout, process.stderr]
  794. , inherit: true,
  795. shell: true,
  796. env: process.env
  797. , runas: processedArgs.runas
  798. }
  799. var cmdseq = [
  800. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  801. , targetrepooptions ]
  802. // , ['git', ['push', targetrepooptions ] // manual push for now..
  803. ]
  804. return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e)})
  805. }
  806. , 'filter-repo' : function(args){
  807. // Merge source repo into target repo
  808. var args = args || {
  809. folder : 'server'
  810. , remotebase : 'http://git.bbh/chess/'
  811. , targetrepo : 'elixir-server'
  812. }
  813. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  814. , inherit: true, shell: true
  815. , env: process.env
  816. , runas: processedArgs.runas
  817. }
  818. var cmdseq = [
  819. // git checkout -b feature/merge-old-project
  820. // git remote add src-project ../src-project
  821. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  822. ]
  823. return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e); throw 'failed' })
  824. }
  825. , 'filter-branch' : function(preservefolder, repo){
  826. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  827. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  828. // Preserve a specific folder.
  829. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  830. /*
  831. git clone repo reposplit
  832. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  833. git remote rm origin
  834. */
  835. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  836. }
  837. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  838. // // Merge repo2 into a subfolder in repo1
  839. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  840. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  841. // /*
  842. // cd repo1
  843. // git remote add -f tempmergesource ../{{mergesource}}/.git
  844. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  845. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  846. // git commit
  847. // // Repair History
  848. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  849. // #!/usr/bin/env bash
  850. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  851. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  852. // subdir=server
  853. // git filter-branch --tree-filter '
  854. // first='"$first"'
  855. // last='"$last"'
  856. // subdir='"$subdir"'
  857. // log_file=/tmp/filter.log
  858. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  859. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  860. // echo "=== $GIT_COMMIT: making changes"
  861. // files=$(git ls-tree --name-only $GIT_COMMIT)
  862. // mkdir -p $subdir
  863. // for i in $files; do
  864. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  865. // done
  866. // else
  867. // echo "=== $GIT_COMMIT: ignoring"
  868. // fi \
  869. // >> $log_file
  870. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  871. // status=0 # tell tree-filter never to fail
  872. // '
  873. // git remote rm tempmergesource
  874. // */
  875. // // better alternative for history
  876. // /**
  877. // *
  878. // git clone git@server.com:old-project.git
  879. // git clone git@server.com:new-project.git
  880. // cd old-project
  881. // mkdir old-project
  882. // git mv !(old-project) old-project
  883. // ls -la and gt mv hidden files ....
  884. // git commit -a -S -m “Moving old project into its own subdirectory”
  885. // cd ../new-project
  886. // git remote add old-project ../old-project
  887. // git fetch old-project
  888. // git checkout -b feature/merge-old-project
  889. // git merge -S --allow-unrelated-histories old-project/master
  890. // git push origin feature/merge-old-project
  891. // git remote rm old-project
  892. // */
  893. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  894. // }
  895. , 'pull' : (label) => {
  896. // Usage :
  897. // elxr pull -- Defaults to run config
  898. return elxr.getpulltask(selectedinstance)()
  899. }
  900. , 'isInstalled': () => {
  901. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  902. console.log(processedArgs._[1] + ' exists.')
  903. return true;
  904. });
  905. }
  906. , 'i' : () => {
  907. var tasks = []
  908. // tasks.push(op['pull']);
  909. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
  910. tasks.push(op['use'])
  911. if (!__isElevated) {
  912. tasks.push(op['npmi'])
  913. }
  914. // var tasksdefs = [
  915. // ['elxr', ['pull']]
  916. // , ['elxr', ['use', 'elixir']]
  917. // , ['elxr', ['npmi']]
  918. // ]
  919. // tasksdefs.forEach(tasksdef=>{
  920. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  921. // })
  922. return any(tasks);
  923. }
  924. , 'npmi': () => {
  925. var tasks = [];
  926. // Build fails without babel...
  927. tasks.push(getShellTask(
  928. 'npm',[ 'i', '-g', 'babel-cli' ]
  929. ) )
  930. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  931. npmbuildrepos = []
  932. npmbuildrepos.forEach(repo => {
  933. tasks.push(() => {
  934. return nodeShellExec('npm', ['i --force'], {
  935. inherit: true, shell: true
  936. , cwd: instanceroot + '/' + repo
  937. , env: process.env
  938. , title: `npm i for ${repo}`
  939. }).catch((e) => {
  940. console.error('Ignoring Benign Error'); console.error(e);
  941. }).then(() => {
  942. console.log(`--npm run build for ${repo}--------------------`)
  943. return nodeShellExec('npm', ['run build'], {
  944. inherit: true, shell: true
  945. , cwd: instanceroot + '/' + repo
  946. , env: process.env
  947. , title: `npm run build for ${repo}`
  948. }).then(Tasq.then).catch(Tasq.catch)
  949. })
  950. })
  951. })
  952. any(tasks).then(() => {
  953. gitRepos.push('client/server');
  954. gitRepos = gitRepos.concat(elevatedRunasRepos);
  955. // gitRepos = [
  956. // // 'bbhverse', 'serververse', 'elixir-server',
  957. // // 'clientverse',
  958. // 'client'
  959. // ];
  960. var rmtasks = []
  961. var repotasks = []
  962. var env = Object.assign({}, process.env)
  963. delete env.NODE_ENV
  964. gitRepos.forEach(repodef => {
  965. rmtasks.push(
  966. // () => {
  967. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  968. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  969. nodeShellExec('rm', ['package-lock.json'], {
  970. inherit: true, shell: true
  971. , cwd: instanceroot + '/' + repodef.repo
  972. , env: process.env
  973. , title: `rm 'package-lock.json' for ${repodef.repo}`
  974. })
  975. .then(()=>{
  976. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  977. }).catch((e) => { console.error(e) })
  978. // }
  979. )
  980. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  981. repotasks.push(
  982. () => {
  983. console.log(`--npm i for ${repodef.repo}--------------------`)
  984. var p = nodeShellExec('npm', ['i', '--force'], {
  985. inherit: true, shell: true
  986. , cwd: instanceroot + '/' + repodef.repo
  987. , env
  988. , title: `npm i for ${repodef.repo}`
  989. }).then(Tasq.then).catch(Tasq.catch)
  990. return p;
  991. })
  992. }
  993. })
  994. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  995. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  996. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  997. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  998. // Second time try also doesnt work.
  999. // repotasks.push(
  1000. // () => {
  1001. // var env = Object.assign({}, process.env)
  1002. // delete env.NODE_ENV
  1003. // console.log(`--------------------second time npm i for client--------------------`)
  1004. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  1005. // // return nodeShellExec('npm', ['i --force'], {
  1006. // inherit: true, shell: true
  1007. // , cwd: instanceroot + '/' + 'client'
  1008. // , env
  1009. // , title: `npm i for client`
  1010. // }).then(Tasq.then).catch(Tasq.catch)
  1011. // })
  1012. var bowerRepos = [{ repo : 'client'}]
  1013. bowerRepos.forEach(repodef => {
  1014. repotasks.push(() => {
  1015. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
  1016. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  1017. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  1018. inherit: true, shell: true
  1019. , cwd: instanceroot + '/' + repodef.repo
  1020. , env: process.env
  1021. , title: `bower i for ${repodef.repo}`
  1022. }).then(Tasq.then).catch(Tasq.catch)
  1023. return p;
  1024. })
  1025. })
  1026. // console.log('rmtasks.length : ' + rmtasks.length)
  1027. return Promise.all(rmtasks).then(() => any(repotasks));
  1028. }).catch(e => {
  1029. }).finally(statuslog.finally)
  1030. }
  1031. , 'start': (label) => {
  1032. console.log('Starting Elixir Server.');
  1033. var env = Object.assign({}, process.env); // Shallow clone it.
  1034. // console.dir(env)
  1035. env.NODE_ENV = process.env.NODE_ENV || 'development';
  1036. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  1037. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  1038. // cmd = 'node'
  1039. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
  1040. var childPromise = nodeShellExec(...cmd, {
  1041. // inherit : true,
  1042. shell: true,
  1043. detached: true,
  1044. stdio: 'ignore',
  1045. cwd: instanceroot + '/' + 'elixir-server'
  1046. , env: env
  1047. })
  1048. var child = childPromise.process;
  1049. if (typeof child.pid !== 'undefined') {
  1050. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1051. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  1052. encoding: 'utf8'
  1053. })
  1054. }
  1055. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  1056. // inherit : true,
  1057. // shell: true, detached: true,
  1058. // cwd : 'qms/server',
  1059. // env: env,
  1060. // shell : true
  1061. // })
  1062. // nodeShellExec('ember', ['s'], {
  1063. // // inherit : true,
  1064. // shell: true, detached: true,
  1065. // cwd : 'client/',
  1066. // env: env
  1067. // })
  1068. console.log('Starting Elixir Client Host.');
  1069. var cmd = ['ember', ['s']]
  1070. var childPromise = nodeShellExec(...cmd, {
  1071. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  1072. // PB : TODO -- ember debugging.
  1073. // inherit : true,
  1074. shell: true,
  1075. detached: true,
  1076. stdio: 'ignore',
  1077. cwd: instanceroot + '/' + 'client'
  1078. , env: env
  1079. })
  1080. // .catch(e=>console.error(e))
  1081. child = childPromise.process;
  1082. if (typeof child.pid !== 'undefined') {
  1083. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1084. fs.writeFileSync('.client.server.pid', child.pid, {
  1085. encoding: 'utf8'
  1086. })
  1087. }
  1088. }
  1089. , 'stop': (label) => {
  1090. const kill = require('tree-kill');
  1091. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  1092. encoding: 'utf8'
  1093. })
  1094. fs.unlinkSync('.elixir-server.elixir.server.pid')
  1095. console.log(serverPid)
  1096. kill(serverPid)
  1097. serverPid = fs.readFileSync('.client.server.pid', {
  1098. encoding: 'utf8'
  1099. })
  1100. fs.unlinkSync('.client.server.pid')
  1101. console.log(serverPid)
  1102. kill(serverPid)
  1103. }
  1104. , 'model' : () => {
  1105. if (__isElevated) {
  1106. var tasks = [
  1107. () => {
  1108. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  1109. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  1110. inherit: true, shell: true
  1111. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  1112. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  1113. , env: process.env
  1114. }).catch((e) => { console.error(e) })
  1115. return p;
  1116. }
  1117. ];
  1118. return any(tasks).then(() => {
  1119. fs.writeFileSync('run.done', 'success')
  1120. }).catch(() => {
  1121. fs.writeFileSync('run.done', 'error')
  1122. })
  1123. }
  1124. else return op['runas']()
  1125. }
  1126. , 'use' : () => {
  1127. // use a certain named instance.
  1128. // Eg :
  1129. // 1) elxr use elixir
  1130. // 2) elxr use cihsr
  1131. // If environment is not specified defaults to development.
  1132. // 1) NODE=test elxr use elixir
  1133. /*// Steps
  1134. 1) Delete Config and Data symlinks
  1135. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  1136. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  1137. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1138. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  1139. */
  1140. var runconfig = { NODE_ENV: repomanifest.node_env }
  1141. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  1142. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  1143. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  1144. runconfig.NODE_ENV && runconfig.NODE_ENV === (repomanifest.node_env || runconfig.NODE_ENV) &&
  1145. repomanifest.instanceName && runconfig.use === repomanifest.instanceName) {
  1146. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  1147. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  1148. return
  1149. }
  1150. var tasks = [
  1151. () => {
  1152. if (existsSync('config')) {
  1153. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  1154. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  1155. return p;
  1156. }
  1157. else return Promise.resolve(true);
  1158. },
  1159. () => {
  1160. if (existsSync('data')) {
  1161. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  1162. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  1163. return p;
  1164. }
  1165. else return Promise.resolve(true);
  1166. },
  1167. ];
  1168. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  1169. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  1170. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  1171. // console.log(process.env.cwd)
  1172. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  1173. // Maps an environment to a branch. Not required if the branch is appropriately named.
  1174. var checkoutMap = { 'development': 'master' }
  1175. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  1176. var performPullOrCloneForBranch = (def)=>{
  1177. var promise = Promise.resolve(true)
  1178. if (!branch) {
  1179. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1180. promise = nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{ branch = __branch})
  1181. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1182. }
  1183. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e )})
  1184. }
  1185. var performCloneAndCheckout = null;
  1186. // cant use git checkout -b it fails when branch already exists.
  1187. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1188. return performPullOrCloneForBranch(def).then(()=>{
  1189. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1190. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1191. // inherit : true, shell: true,
  1192. cwd: instanceroot + '/' + def.repo
  1193. // , stdio : ignore // Use when we want to silence output completely.
  1194. , runas: processedArgs.runas
  1195. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  1196. }).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 } })
  1197. })
  1198. }
  1199. // var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  1200. // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  1201. var elevatedqueue = [];
  1202. var enqueueOnce = (queue, task, def) => {
  1203. var found = queue.find(element => {
  1204. var keys = Object.keys( element )
  1205. for(var k=0; k < keys.length; k++) {
  1206. if(element[keys[k]] !== def[k]) return false;
  1207. }
  1208. })
  1209. queue.push(function(){ return task(this)}.bind(def));
  1210. }
  1211. var enqueue = (queue, task, def) => {
  1212. queue.push(function(){ return task(def)}.bind(def));
  1213. }
  1214. var mergeSources = {
  1215. 'development': null,
  1216. 'test': 'master',
  1217. 'production': 'master'
  1218. }
  1219. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1220. // Checkout is reduced to pull provided the current branch is the targetbranch
  1221. if(branch === mergesource) performCheckout = (def) => {
  1222. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1223. return nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{
  1224. if(branch === __branch) return performCloneAndCheckout(def)
  1225. return performPullOrCloneForBranch(def)
  1226. })
  1227. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1228. }
  1229. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  1230. var performPullAll = (def) => {
  1231. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1232. return nodeShellExec('git', ['pull', '--all'], {
  1233. // inherit : true, shell: true,
  1234. cwd: instanceroot + '/' + def.repo
  1235. , runas: processedArgs.runas
  1236. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  1237. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  1238. }
  1239. var excludeCheckouts = Object.assign(exludeMergeRepos)
  1240. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  1241. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  1242. var performMerge = (def) => {
  1243. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  1244. return nodeShellExec('git', ['merge', mergesource], {
  1245. inherit: true, shell: true,
  1246. cwd: instanceroot + '/' + def.repo
  1247. , runas: processedArgs.runas
  1248. }).catch((e) => { console.error(e) })
  1249. }
  1250. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
  1251. // var performRepoOperation = function(def) {
  1252. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  1253. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  1254. // }
  1255. return any(tasks).then(() => {
  1256. var pr = Promise.resolve(true)
  1257. if (!__isElevated) {
  1258. pr = op['runas']()
  1259. return pr.then(()=>{
  1260. //target is the env is we specify in elxr use command. Default is dev
  1261. //Switch to target branch
  1262. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  1263. // pull or clone target branch
  1264. .then(() => {
  1265. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1266. return any(gitRepos.map((repo) => performPullAll(repo)))
  1267. })
  1268. // switch to source branch
  1269. .then( () => {
  1270. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  1271. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  1272. })
  1273. //Pull on merge source branch
  1274. .then( () => {
  1275. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1276. return any(gitRepos.map((repo) => performPullAll(repo)))
  1277. })
  1278. //Switch to target branch
  1279. .then( () => {
  1280. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1281. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  1282. })
  1283. .then( //Merge source branch to target branch
  1284. () => {
  1285. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1286. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
  1287. })
  1288. })
  1289. }
  1290. else {
  1291. tasks = [
  1292. () => {
  1293. // Use junctions to avoid npm package issues
  1294. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  1295. inherit: true, shell: true
  1296. , cwd : instanceroot
  1297. , env: process.env
  1298. }).catch((e) => { console.error(e) })
  1299. return p;
  1300. }
  1301. ];
  1302. if (processedArgs._[1]) {
  1303. tasks = tasks.concat(
  1304. [
  1305. () => {
  1306. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  1307. inherit: true, shell: true
  1308. , cwd : instanceroot
  1309. , env: process.env
  1310. }).catch((e) => { console.error(e) })
  1311. return p;
  1312. }
  1313. ]
  1314. )
  1315. }
  1316. return any(tasks).then(()=>{
  1317. // checkout target branch
  1318. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1319. // pull or clone target branch
  1320. .then(() => {
  1321. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1322. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  1323. })
  1324. // switch to source branch
  1325. .then( () => {
  1326. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1327. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  1328. })
  1329. //Pull on merge source branch
  1330. .then( () => {
  1331. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1332. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  1333. })
  1334. //Switch to target branch
  1335. .then( () => {
  1336. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1337. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1338. })
  1339. .then( //Merge source branch to target branch
  1340. () => {
  1341. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1342. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
  1343. })
  1344. .then(() => {
  1345. fs.writeFileSync('run.done', 'success')
  1346. }).catch(() => {
  1347. fs.writeFileSync('run.done', 'error')
  1348. })
  1349. })
  1350. }
  1351. }).catch(() => {
  1352. fs.writeFileSync('run.done', 'error')
  1353. })
  1354. // Antibiotic stewardship program.
  1355. // 1st use is fine.
  1356. // Max vials dispense
  1357. // 2nd use Pharmacy needs justification Form.
  1358. // Approval after a certain period of time.
  1359. }
  1360. , 'g': () => {
  1361. if (processedArgs.h) {
  1362. console.log('elxr g [modelname] => generate a model named [modelname]');
  1363. console.log('elxr g => regenerate all known models');
  1364. return
  1365. }
  1366. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1367. // console.log('Starting directory: ' + process.cwd());
  1368. // try {
  1369. // child = child.on('close', () => { process.chdir(label) } );
  1370. // console.log('New directory: ' + process.cwd());
  1371. // }
  1372. // catch (err) {
  1373. // console.log('chdir: ' + err);
  1374. // }
  1375. // child.on('close', function(){
  1376. // var options = {
  1377. // shell : true
  1378. // , inherit : true
  1379. // // , cwd : '' + process.cwd
  1380. // // , env : process.env
  1381. // };
  1382. // nodeShellExec('git', ['init'], { inherit : true});
  1383. if (0) {
  1384. // PB : TODO -- Special google chrome profile for tests etc.
  1385. nodeShellExec('pwd', { inherit: true });
  1386. // /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"
  1387. // "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
  1388. // "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
  1389. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1390. "--profile-directory=Profile 1"
  1391. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1392. }
  1393. // nodeShellExec('npm', ['init', '-y'], options);
  1394. // nodeShellExec('npm', ['init', '-y'], options);
  1395. // })
  1396. var g = {
  1397. 'client': () => {
  1398. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  1399. console.info('Creating new ember client named : ' + processedArgs._[2]);
  1400. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1401. stdio: ['pipe', process.stdout, process.stderr],
  1402. inherit: true,
  1403. shell: true,
  1404. cwd: path.dirname(__dirname),
  1405. env: env
  1406. })
  1407. },
  1408. 'modelr': () => {
  1409. var tasks = [
  1410. () => {
  1411. var p = nodeShellExec('"ember"', [
  1412. 'g'
  1413. , 'modelr'
  1414. , processedArgs._[2]], {
  1415. inherit: true, shell: true, env: process.env
  1416. }).then(() => {
  1417. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  1418. return true;
  1419. }).catch((e) => { console.error(e) })
  1420. return p;
  1421. },
  1422. () => {
  1423. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1424. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  1425. chromeprefs = JSON.parse(chromeprefs)
  1426. var previous = chromeprefs.download.default_directory;
  1427. var parentDir = path.dirname(__dirname);
  1428. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1429. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1430. // PB : TODO -- detect where chrome is installed.
  1431. // PB : TODO -- set the download dir to the place where files are needed.
  1432. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1433. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1434. , '--profile-directory="chess"'
  1435. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1436. inherit: true, shell: true
  1437. , env: process.env
  1438. }).then(() => {
  1439. chromeprefs.download.default_directory = previous;
  1440. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1441. return true;
  1442. }).catch((e) => { console.error(e) })
  1443. return p;
  1444. }
  1445. ,
  1446. () => {
  1447. console.log('Browser process should have closed here....')
  1448. return true;
  1449. }
  1450. ]
  1451. any(tasks)
  1452. }
  1453. }
  1454. g[processedArgs._[1]]();
  1455. }
  1456. }
  1457. var util = require('util');
  1458. var cliname = 'elxr';
  1459. var ver = '1.1';
  1460. var readme = `
  1461. Command syntax examples
  1462. elxr
  1463. Displays help. Same as elxr h
  1464. elxr i
  1465. Runs interactive propmts to help choose installation options.
  1466. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  1467. General command syntax.
  1468. Eg: NODE_ENV=development elxr pull elixir
  1469. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  1470. The specific cmd defines what the value is interpreted as.
  1471. There are several cmds that do not require an {{instancename}} parameter.
  1472. Eg: elxr remote remove origin
  1473. Git operations or passthrough external commands on all repository folders in you working directory.
  1474. Main objectives.
  1475. elxr cli is a wrapper around other shell commands and api based operations.
  1476. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  1477. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  1478. `;
  1479. var help = `
  1480. ${readme}
  1481. # list of commands... please refer dveloper documentation for ${cliname}
  1482. ${
  1483. // util.inspect(
  1484. [Object.keys(op)]
  1485. // )
  1486. }
  1487. `;
  1488. var elxr = {
  1489. help() {
  1490. return chalk.cyanBright(`
  1491. -------------------------------------------------------------------------------
  1492. *** BBH Elixir ***
  1493. -------------------------------------------------------------------------------
  1494. elxr ${ver}
  1495. A cli tool for chess
  1496. ${help}
  1497. -------------------------------------------------------------------------------
  1498. `)
  1499. }
  1500. , info() {
  1501. return chalk.cyanBright(`
  1502. -------------------------------------------------------------------------------
  1503. *** BBH Elixir ***
  1504. -------------------------------------------------------------------------------
  1505. elxr ${ver}
  1506. A cli tool for chess
  1507. -------------------------------------------------------------------------------
  1508. `)
  1509. }
  1510. , getpulltask(def){
  1511. def = (def ? (
  1512. def.requiresElevation = true,
  1513. def.reqularRepos = def.repos,
  1514. def.elevatedRepos = def.elevatedRunasRepos
  1515. ) : false) || {
  1516. requiresElevation : true,
  1517. reqularRepos : gitRepos,
  1518. elevatedRepos : elevatedRunasRepos
  1519. }
  1520. console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  1521. console.dir(def)
  1522. var env = Object.assign({}, process.env); // Shallow clone it.
  1523. console.log('Running exlr pull : ' + path.dirname(__dirname))
  1524. var useGitPull = processedArgs.useGitPull || false;
  1525. if(def.elevatedRepos || def.reqularRepos) {
  1526. if(def.elevatedRepos) def.requiresElevation = true;
  1527. else delete def.requiresElevation;
  1528. }
  1529. else {
  1530. if(def.requiresElevation) def.elevatedRepos = [def]
  1531. else def.reqularRepos = [def]
  1532. }
  1533. var elevatedpulltasks = null;
  1534. var regularpulltasks = function(){ return Promise.resolve(true) }
  1535. if(def.elevatedRepos){
  1536. elevatedpulltasks = function() {
  1537. return any(def.elevatedRepos.map((def) => performPull(def.repo))).then(() => {
  1538. return true;
  1539. }).catch((e) => {
  1540. console.error(e)
  1541. })
  1542. }
  1543. }
  1544. if(def.reqularRepos) {
  1545. var regularpulltasks = function(){
  1546. var pendingpulls = [];
  1547. def.reqularRepos.forEach((def) => { pendingpulls.push(performPull(def.repo)) })
  1548. return Promise.all(pendingpulls).finally(Traq.finally)
  1549. }
  1550. }
  1551. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1552. else return getTaskWithoutElevation({ regularpulltasks})
  1553. }
  1554. }
  1555. function preworkerconfig(){
  1556. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  1557. gitRepos = repomanifest.repos
  1558. // gitRepos = ['chess-server-lib'];
  1559. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  1560. elevatedRunasRepos = repomanifest.elevated
  1561. // Repos that should excluded from merge for releases...
  1562. exludeMergeRepos = repomanifest.exludeMergeRepos
  1563. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  1564. // mysql -u root -p db_name < drop_all_tables.sql
  1565. var mysql = '../xampp/mysql/bin/mysql'
  1566. var mysqldump = '../xampp/mysql/bin/mysqldump'
  1567. }
  1568. // The main elxr cli process
  1569. function elxrworker() {
  1570. var subcommandlabels = {
  1571. remote : (`remote ${processedArgs._[1] || ''}`).trim()
  1572. }
  1573. var __runcmd = function (label) {
  1574. var distinquishedlabel = subcommandlabels[label] || label
  1575. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  1576. }
  1577. // --runas
  1578. if (processedArgs.runas) {
  1579. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  1580. return __runcmd('runas')
  1581. }
  1582. else return __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  1583. }
  1584. var getManifest = function () {
  1585. // Once choices are made we need to load config according to those choices.
  1586. // No trace of a previous run...
  1587. // Default Config...
  1588. return repomanifest = selectedinstance;
  1589. }
  1590. function acquireChoices(selectedinstance) {
  1591. var hasconfig = false;
  1592. console.warn(chalk.yellow(`
  1593. -------------------------------------------------------------------------------
  1594. Warning : Cannot locate your preferred configuration since it was not specified
  1595. You should fork the default chess configuration to customize and make it
  1596. your own instance with a named config as
  1597. {{yourowninstancename}}-config-{{yourchosenenvironment}}
  1598. And then run this tool as follows
  1599. NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  1600. OR
  1601. Run this tool with the following command to use a quick start default.
  1602. elxr --default
  1603. OR
  1604. Choose one of the options below to run interactively.
  1605. We will run your choice at the next prompt.
  1606. -------------------------------------------------------------------------------
  1607. `))
  1608. var prompt = cli.prompter;
  1609. return prompt.ask(`Choose an option :
  1610. d) Install the default chess instance.
  1611. => elxr i chess node_env=development --default
  1612. n) Create your custom new instance interactively
  1613. => elxr i {{instanceName}} node_env={{environment}}
  1614. i) Choose an instance and environment to install
  1615. => elxr i {{instanceName}} node_env={{environment}}
  1616. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  1617. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  1618. h) Help
  1619. q) Quit
  1620. Default <= d
  1621. : `).then((choice) => {
  1622. if (choice && choice === 'd' || !choice) {
  1623. processedArgs._[0] = 'i'
  1624. selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  1625. selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  1626. selectedinstance.reposerver = 'https://git.bbh.org.in'
  1627. getManifest() // PB : TODO -- acquire the manifest directly from http url instead of clone before cloning the config. Since
  1628. // This is because the manifest at any server location can redirect to the preferred server..
  1629. }
  1630. else if (choice === 'h') {
  1631. processedArgs._[0] = 'h'
  1632. fs.writeFileSync('run.done', 'noop help');
  1633. console.log(elxr.help()); process.exit()
  1634. }
  1635. else if (choice === 'n' || choice === 'i') {
  1636. var p1 = cli.prompter;
  1637. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1638. processedArgs._[0] = 'i'
  1639. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  1640. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1641. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1642. if (choice === 'n') {
  1643. selectedinstance.reposerver = 'https://git.bbh.org.in'
  1644. console.warn(
  1645. chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  1646. process.exit();
  1647. }
  1648. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1649. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1650. })
  1651. })
  1652. })
  1653. } else if (choice === 'c') {
  1654. var p1 = cli.prompter;
  1655. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1656. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  1657. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1658. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1659. return p1.ask(`Enter cmd :
  1660. p) pull
  1661. Default <= p
  1662. : `).then(function (cmd) {
  1663. if (!cmd || cmd === 'p') {
  1664. processedArgs._[0] = 'pull'
  1665. }
  1666. else processedArgs._[0] = cmd
  1667. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1668. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1669. })
  1670. })
  1671. })
  1672. })
  1673. } else {
  1674. 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.`));
  1675. fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  1676. fs.writeFileSync('run.done', 'noop quit');
  1677. process.exit()
  1678. }
  1679. })
  1680. }
  1681. var acquireConfig = function (selected, chessinstances) {
  1682. var configrepo = selected.instanceName + '-config-' + selected.node_env;
  1683. return performPull(configrepo).then(() => {
  1684. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  1685. repomanifest = require(manifestpath)()
  1686. chessinstances = chessinstances || {};
  1687. chessinstances[selected.instanceName] = chessinstances[selected.instanceName] || {}
  1688. chessinstances[selected.instanceName][selected.node_env] = chessinstances[selected.instanceName][selected.node_env] || {}
  1689. chessinstances['current_run'] = { instanceName: selected.instanceName, node_env: selected.node_env }
  1690. // Config from server always override merges into selection ecept for the current selection.
  1691. selectedinstance = utils.assign(chessinstances[selected.instanceName][selected.node_env], selected, repomanifest)
  1692. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  1693. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  1694. // PB : TODO -- We should probably write the new server config also...
  1695. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  1696. ENV.NODE_ENV = selectedinstance.node_env;
  1697. })
  1698. .catch((e) => {
  1699. console.error(e)
  1700. console.error('Config acquisition failed.')
  1701. })
  1702. }
  1703. var launchpath = process.cwd().replace(/\\/, '/')
  1704. var thisscriptdir = __dirname
  1705. var instanceroot = launchpath;
  1706. var detectInstance = function () {
  1707. console.log(`launchpath = ${launchpath}`)
  1708. console.log(`thisscriptdir = ${thisscriptdir}`)
  1709. var root = launchpath;
  1710. // We need a reference to the root director for elxr cli to be properly oriented.
  1711. if ((launchpath + path.normalize('/elxr')) === thisscriptdir) {
  1712. // We ran unbuilt from the proper root with elxr subfolder.
  1713. console.log(`Instance Path : ${root}`)
  1714. }
  1715. else {
  1716. if (launchpath === thisscriptdir) {
  1717. // Same directory doesn't mean we are being run from elxr directory or the root directory.
  1718. // It could be a standalone elxr build which may or maynot be in the proper location.
  1719. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  1720. // Unbuilt therefore we are in the elxr directory.
  1721. root = path.normalize(launchpath + '/..');
  1722. }
  1723. else {
  1724. // Built version.
  1725. // check if we have a elxr subfolder.
  1726. if (fs.existsSync(launchpath + '/..' + path.normalize('/elxr'))) {
  1727. // Probably in the right place.
  1728. root = path.normalize(launchpath + '/..');
  1729. }
  1730. else {
  1731. // Assume launchpath is meaningless.
  1732. // Figure it out from the input instance name and environment parameters if we are in the right location.
  1733. root = path.normalize(launchpath + '/' + processedArgs._[1] + '/' + processedArgs.node_env)
  1734. }
  1735. }
  1736. }
  1737. }
  1738. instanceroot = root.replace(/\\/, '/');
  1739. __default.root = root;
  1740. return Promise.resolve(__default);
  1741. }
  1742. //
  1743. var __default = {
  1744. // Default is public server only.
  1745. // All public repos are by default available.
  1746. reposervers: ['https://git.bbh.org.in']
  1747. , repos: [
  1748. 'setup'
  1749. , 'elxr'
  1750. , 'loopback-connector-mysql'
  1751. , 'loopback-jsonapi-model-serializer'
  1752. , 'loopback-component-jsonapi'
  1753. , 'ember-service-worker'
  1754. , 'ember-service-worker-asset-cache'
  1755. , 'ember-service-worker-cache-fallback'
  1756. , 'ember-service-worker-index'
  1757. , 'ember-sw-client-route'
  1758. ]
  1759. , elevated: []
  1760. , exludeMergeRepos: {}
  1761. , instanceName: 'chess'
  1762. // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
  1763. , node_env: 'development'
  1764. }
  1765. var __interactve_promts = {
  1766. get reposerver(){
  1767. return cli.prompt(this.reposervers, 'git default repo').then(reposerver => {
  1768. Object.defineProperty(this, 'reposerver', {
  1769. value: reposerver,
  1770. writable: false,
  1771. configurable : true,
  1772. enumerable : true
  1773. });
  1774. return reposerver
  1775. })
  1776. }
  1777. , set reposerver(reposerver){
  1778. Object.defineProperty(this, 'reposerver', {
  1779. value: reposerver,
  1780. writable: false,
  1781. configurable : true,
  1782. enumerable : true
  1783. });
  1784. return reposerver
  1785. }
  1786. }
  1787. var downloadsdir = '../Downloads';
  1788. var prerequisites = [
  1789. {
  1790. shellcmd: 'git',
  1791. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  1792. , installer: 'Git-2.31.0-64-bit.exe'
  1793. , installcmd: ['cmd', ['/c', 'start',
  1794. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  1795. , '/VERYSILENT'
  1796. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  1797. ]]
  1798. , preinstallsteps: function() {
  1799. var prompt = cli.prompter;
  1800. var steps = [
  1801. () => {
  1802. if (!existsSync(downloadsdir + '/' + this.installer)) {
  1803. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  1804. }
  1805. else return Promise.resolve(true)
  1806. }
  1807. ]
  1808. var prompts = [
  1809. () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
  1810. , () => prompt.ask(`git email : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
  1811. ]
  1812. return any([any(steps), any(prompts)])
  1813. }
  1814. , installsteps: function () {
  1815. return any([this.installcmd].map(callsheltask))
  1816. }
  1817. , postinstallsteps: function(){
  1818. var prompt = cli.prompter;
  1819. var gitUser = 'guest';
  1820. var gitEmail = 'guest@bbh.org.in';
  1821. var prompts = [];
  1822. prompts.push(
  1823. ()=>{
  1824. var choices = { 0 : 'guest', 1 : 'chessdemo' }
  1825. return cli.prompt(choices, 'git user name').then(gituser => gitUser = gituser)
  1826. }
  1827. )
  1828. prompts.push(
  1829. ()=>{
  1830. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  1831. return cli.prompt(choices, 'git user email').then(gitemail => gitEmail = gitemail)
  1832. }
  1833. )
  1834. return any(prompts).then(()=>{
  1835. var steps = [
  1836. ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  1837. , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  1838. ]
  1839. return any(steps.map(callsheltask)).then(() => {
  1840. })
  1841. });
  1842. }
  1843. , install: function () {
  1844. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  1845. }
  1846. , verifyAndInstall : function(){
  1847. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  1848. if(exists) {
  1849. // return any(['git', ['config', '--global', '-l']].map(callsheltask))
  1850. return this.getUser(null, this.postinstallsteps.bind(this))
  1851. }
  1852. return this.install();
  1853. });
  1854. }
  1855. , getUser : function(repo, onNoResult){
  1856. onNoResult = onNoResult || function(){return false}
  1857. var globalOrLocal = '--global';
  1858. if(!repo) globalOrLocal = '--global';
  1859. else globalOrLocal = '--local'
  1860. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(callsheltask)).then((result)=>{
  1861. // not yet configured.
  1862. if(!result.success) return onNoResult()
  1863. else {
  1864. var users = result.messages[0].trim().split('\n');
  1865. if(users.length === 0 ||
  1866. users.length === 1 && users[0] === 'guest') {
  1867. return onNoResult()
  1868. }
  1869. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  1870. }
  1871. })
  1872. .catch((e)=>{
  1873. console.log(e)
  1874. return onNoResult()
  1875. })
  1876. }
  1877. }
  1878. ,
  1879. {
  1880. shellcmd: 'node',
  1881. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  1882. , installer: 'node-v14.16.0-x64.msi'
  1883. , installcmd: ['MSIEXEC.exe', ['/i'
  1884. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  1885. , 'ACCEPT=YES', '/passive']]
  1886. , install : function() { return any([this.installcmd].map(callsheltask)).then(() => { }) }
  1887. }
  1888. ]
  1889. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  1890. function ensureDirectoryExistence(filePath) {
  1891. var dirname = path.dirname(filePath);
  1892. if (fs.existsSync(dirname)) {
  1893. return filePath;
  1894. }
  1895. ensureDirectoryExistence(dirname);
  1896. fs.mkdirSync(dirname);
  1897. return filePath;
  1898. }
  1899. var mainTasks = [];
  1900. function verifyAndInstallPrerequisites() {
  1901. fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
  1902. // PB : TODO include and build from files... using rollup..
  1903. var downloadbatch =
  1904. `::**************************************************************************
  1905. :Download_ <url> <File>
  1906. Powershell.exe ^
  1907. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  1908. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  1909. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  1910. exit /b
  1911. ::**************************************************************************`
  1912. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch)
  1913. var windowselevate =
  1914. `
  1915. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  1916. <script language="vbscript">
  1917. document.title = "elxr control panel"
  1918. self.ResizeTo 200,600
  1919. Sub Window_Onload
  1920. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  1921. End Sub
  1922. Set objShell = CreateObject("WScript.Shell")
  1923. Set objENV = objShell.Environment("Process")
  1924. dim NODE_ENV
  1925. NODE_ENV = objENV("NODE_ENV")
  1926. </script>
  1927. <script language="javascript">
  1928. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  1929. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  1930. // alert(windowselevate.commandLine)
  1931. var args = windowselevate.commandLine.split('"').slice(3);
  1932. // alert(args)
  1933. var processedArgs = { _ : [] }
  1934. var namedArgs = [];
  1935. for(var item in args){
  1936. if(args[item].charAt(0) === '-'){
  1937. namedArgs.push(args[item])
  1938. var split = args[item].split('=');
  1939. processedArgs[split[0].slice(2)] = split[1] || true;
  1940. }
  1941. else processedArgs._.push(args[item]);
  1942. }
  1943. // args = args.forEach(function(item){ })
  1944. // alert('processedArgs._ : ' + processedArgs._);
  1945. // alert(processedArgs.runas);
  1946. // PB : TODO -- Convert all the cli args back to string.
  1947. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  1948. // alert(cargs)
  1949. var shell = new ActiveXObject('shell.application');
  1950. // alert('launching node privilged. ' + processedArgs['nodepath'])
  1951. // shell.ShellExecute('where', 'node', '', '', 10);
  1952. shell.ShellExecute('node', cargs, '', 'runas', 1);
  1953. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  1954. var fso = new ActiveXObject('Scripting.FileSystemObject');
  1955. window.onload = function() {
  1956. document.body.style.backgroundColor = 'black';
  1957. document.body.style.fontFamily = 'arial';
  1958. var log = document.createElement('div');
  1959. log.innerHTML='Please Wait';
  1960. function l(msg){ log.innerHTML+= msg; };
  1961. log.style.color = 'blue';
  1962. log.style.width = '95%';
  1963. log.id = 'log';
  1964. document.body.appendChild(log);
  1965. l('<Br/>Current config : ')
  1966. l('<Br/>NODE_ENV = ' + NODE_ENV)
  1967. l('<Br/>cmd = ' + processedArgs._[0])
  1968. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  1969. l('<Br/><Br/>')
  1970. var timer = function(){
  1971. l('.');
  1972. if(fso.FileExists("run.done")) close();
  1973. else window.setTimeout(timer, 1000);
  1974. };
  1975. window.setTimeout(timer, 3000);
  1976. };
  1977. </script>
  1978. </html>
  1979. `
  1980. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate)
  1981. var downloadtasks = [];
  1982. var installtasks = [];
  1983. prerequisites.forEach(preq => {
  1984. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  1985. if (exists) console.log(`${preq.shellcmd} exists`)
  1986. else {
  1987. console.log(`${preq.shellcmd} is not installed`)
  1988. return preq.preinstallsteps.call(preq).then(() => {
  1989. installtasks.push(preq.install.bind(preq))
  1990. })
  1991. }
  1992. }))
  1993. })
  1994. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  1995. }
  1996. var getPromptableAsyncPropDescriptor = function(propName, choices, defaultchoise){
  1997. return {
  1998. get (){
  1999. return cli.prompt( choices, propName, defaultchoise).then(propValue => {
  2000. Object.defineProperty(this, propName, {
  2001. value: propValue,
  2002. writable: false,
  2003. configurable : true,
  2004. enumerable : true
  2005. });
  2006. return propValue
  2007. })
  2008. }
  2009. // , set (propValue){
  2010. // Object.defineProperty(this, propName, {
  2011. // value: propValue,
  2012. // writable: false,
  2013. // configurable : true,
  2014. // enumerable : true
  2015. // })
  2016. // return propValue;
  2017. // }
  2018. , configurable : true
  2019. , enumerable : true
  2020. }
  2021. }
  2022. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  2023. var selectedinstance = null;
  2024. var chessinstances = { current_run : {} };
  2025. acquireElevationState().then(() => {
  2026. var skipprerequisites = false;
  2027. var clioverrides = { }
  2028. function initinstances(chessinstances, selected) {
  2029. chessinstances.current_run.instanceName = processedArgs._[1] = processedArgs._[1] || chessinstances.current_run.instanceName || selected.instanceName;
  2030. chessinstances.current_run.node_env = processedArgs.node_env = processedArgs.node_env || chessinstances.current_run.node_env || selected.node_env;
  2031. chessinstances[chessinstances.current_run.instanceName] = chessinstances[chessinstances.current_run.instanceName] || {}
  2032. // Override sequence.
  2033. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  2034. selectedinstance = Object.assign(
  2035. selected
  2036. , chessinstances[chessinstances.current_run.instanceName][chessinstances.current_run.node_env]
  2037. , clioverrides
  2038. // , __interactve_promts -- Cant just override. Also need selectedinstance to be ready...
  2039. );
  2040. repomanifest = selectedinstance
  2041. return chessinstances
  2042. }
  2043. function acquirelocalinstances(selected){
  2044. var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
  2045. return chessinstances
  2046. }
  2047. var noprerequisites = {
  2048. add : true, 'set-url' : true, 'repo-relocate' : true
  2049. , remote : true
  2050. }
  2051. var skipprereqs = {}
  2052. var maintask = () => {
  2053. // Default cmd to run !
  2054. processedArgs._[0] === processedArgs._[0] || 'pull';
  2055. // selectedinstance.reposerver = repomanifest.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available...
  2056. if(!noprerequisites[processedArgs._[0]]
  2057. && !skipprereqs[processedArgs._[0]]
  2058. ) {
  2059. return prerequisites.git.verifyAndInstall().then(()=>{
  2060. var e = { message : 'verifyAndInstall', success : true}
  2061. return acquireConfig(selectedinstance, chessinstances).catch((err) => {
  2062. e = err;
  2063. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  2064. console.error(err)
  2065. }).then(() => { preworkerconfig(); return elxrworker(true) })
  2066. // .finally(()=>{
  2067. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  2068. // if(!e.success) fs.writeFileSync('run.done', 'error');
  2069. // // return process.exit()
  2070. // })
  2071. })
  2072. }
  2073. else {
  2074. console.log('cmd has no preqs or has been configured to skip preqs')
  2075. preworkerconfig()
  2076. return elxrworker()
  2077. }
  2078. }
  2079. const retaincount = 2
  2080. var min = runtimestamp;
  2081. var collect = []
  2082. if(noprerequisites[processedArgs._[0]]
  2083. || skipprereqs[processedArgs._[0]]
  2084. ) {
  2085. return elxrworker()
  2086. }
  2087. return detectInstance().then((detectedInstance)=>{
  2088. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  2089. processedArgs.node_env ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env
  2090. : (process.env.NODE_ENV && process.env.NODE_ENV.trim()) ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()): null;
  2091. selectedinstance = Object.assign(detectedInstance, clioverrides);
  2092. var todo = Promise.resolve(true);
  2093. var promptkeys = { 'instanceName' : processedArgs._[1] }
  2094. var reconfirm = {
  2095. 'instanceName' : selectedinstance['instanceName'] === 'chess'
  2096. }
  2097. var prompts = [];
  2098. var eachPrompt = function(k, i, a){
  2099. // No local instances config found. We use a default initialized instance available in selectedinstance
  2100. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  2101. if(promptkeys[k] && selectedinstance[k] !== promptkeys[k] || promptkeys[k] === undefined && selectedinstance[k] === undefined
  2102. || reconfirm[k]) {
  2103. prompts.push(async ()=>{
  2104. // PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
  2105. // We take a snapshot... Shallow.. !! If required deep should be used based on use case.
  2106. // If latest altered state is required we can reerence this directly.
  2107. // var asyncthis = Object.assign(this);
  2108. Object.defineProperty(selectedinstance, k, getPromptableAsyncPropDescriptor(k, choices[k], promptkeys[k] || selectedinstance[k] ));
  2109. return await selectedinstance[k]
  2110. })
  2111. }
  2112. delete promptkeys[k]
  2113. }
  2114. try {
  2115. chessinstances = acquirelocalinstances(selectedinstance);
  2116. initinstances(chessinstances, selectedinstance)
  2117. var instanceNameChoices = new Set(Object.keys( chessinstances) )
  2118. instanceNameChoices.delete('current_run')
  2119. instanceNameChoices.add(selectedinstance['instanceName'])
  2120. if(promptkeys['instanceName']) instanceNameChoices.add(promptkeys['instanceName'])
  2121. var choices = {
  2122. 'instanceName' : Array.from(instanceNameChoices)
  2123. , 'reposerver' : selectedinstance['reposervers']
  2124. }
  2125. Object.keys(__interactve_promts).forEach(eachPrompt, __interactve_promts)
  2126. Object.keys(promptkeys).forEach(eachPrompt, promptkeys)
  2127. todo = any(prompts).then(()=>{ return selectedinstance })
  2128. }
  2129. catch (e) {
  2130. console.error(e) // Missing chessinstances is not an error...
  2131. initinstances(chessinstances, selectedinstance)
  2132. var instanceNameChoices = new Set(Object.keys( chessinstances) )
  2133. instanceNameChoices.delete('current_run')
  2134. instanceNameChoices.add(selectedinstance['instanceName'])
  2135. if(promptkeys['instanceName']) instanceNameChoices.add(promptkeys['instanceName'])
  2136. var choices = {
  2137. 'instanceName' : Array.from(instanceNameChoices)
  2138. , 'reposerver' : selectedinstance['reposervers']
  2139. }
  2140. Object.keys(__interactve_promts).forEach(eachPrompt, __interactve_promts)
  2141. Object.keys(promptkeys).forEach(eachPrompt, promptkeys)
  2142. todo = any(prompts).then(()=>{ return selectedinstance })
  2143. if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  2144. // Weve been told what to do.
  2145. todo = todo.then(() => { return acquireChoices(selectedinstance) })
  2146. }
  2147. todo = todo.then(() => {
  2148. try {
  2149. chessinstances = acquirelocalinstances(selectedinstance)
  2150. initinstances(chessinstances, selectedinstance)
  2151. }
  2152. catch (e) {
  2153. console.error(e)
  2154. console.log('No local instances config found in current root = ' + selectedinstance.root);
  2155. console.log('A config will be createed with the instance and environment chosen...')
  2156. // return (async ()=>{return await __default.reposerver})().then(()=>{
  2157. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  2158. // return selectedinstance = Object.assign(__default, selectedinstance);
  2159. // })
  2160. return selectedinstance
  2161. }
  2162. })
  2163. }
  2164. return todo
  2165. })
  2166. .then(()=>{
  2167. if(!__isElevated) {
  2168. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/readme.txt`)
  2169. // collect garbage
  2170. return dirs( (dir)=>{
  2171. var matches = /run-(.*)/gm.exec(dir.name)
  2172. if(matches) {
  2173. if(+(matches[1]) < min) {
  2174. min = matches[1]
  2175. collect.splice( 0, 0, matches[1] )
  2176. }
  2177. else collect.push(matches[1])
  2178. }
  2179. }, `${selectedinstance.root}/.elxr` ).then(()=>{
  2180. // delete garbage
  2181. if(collect.length > retaincount) {
  2182. var asyncs = [];
  2183. while((collect.length - asyncs.length) > retaincount) {
  2184. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  2185. }
  2186. return Promise.all(asyncs)
  2187. }
  2188. else return true
  2189. })
  2190. }
  2191. else return true;
  2192. })
  2193. .then(()=>{
  2194. // PB : TODO -- Keep only the last n runs...
  2195. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  2196. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
  2197. if (!skipprerequisites && !__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
  2198. mainTasks.push(maintask)
  2199. return any(mainTasks);
  2200. })
  2201. })
  2202. // detect if alread installed -> Take no action.
  2203. // download if no installer avalable -> next()
  2204. // install
  2205. function chackandinstall(items) {
  2206. var tasks = []
  2207. items.forEach(item => {
  2208. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  2209. })
  2210. return Promise.all(tasks).then(existances => {
  2211. existances.forEach((exists, i) => {
  2212. if (!exists) {
  2213. return downloadandinstall([items[i]])
  2214. }
  2215. })
  2216. })
  2217. }
  2218. function downloadandinstall(items) {
  2219. var tasks = []
  2220. items.forEach(item => {
  2221. tasks.push(getTaskDownload(item))
  2222. })
  2223. return Promise.all(tasks)
  2224. }
  2225. // Sample instances config.
  2226. // var instances = {
  2227. // "elixir": {
  2228. // "production": {
  2229. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  2230. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  2231. // , "exludeMergeRepos": {
  2232. // "elixir-config-development": true, "elixir-config-test": true
  2233. // , "elixir-config-production": true, "elixir-data": true
  2234. // }
  2235. // , "instanceName": "elixir", "node_env": "production"
  2236. // }
  2237. // },
  2238. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  2239. // }
  2240. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...