選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

index.js 135KB

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