555
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

index.js 138KB

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