您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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