555
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

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