Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

index.js 110KB

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