You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

elxr.js 103KB

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