555
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

index.js 132KB

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