Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  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. // 'use strict';
  12. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  13. // PB : TODO --
  14. // runas bypass non elevated tasks when we request privelege
  15. // runas message is always error needs to be fixed.
  16. // runas wait needs to be parallelized.
  17. // suppress elevation check error messages
  18. // support runas lauched directly from shell.
  19. // pass in environment in hta to shellexecute.
  20. const { existsSync } = require('fs');
  21. const fs = require('fs')
  22. const cliargs = utils.cliargs;
  23. const processedArgs = cliargs(process.argv.slice(2));
  24. console.dir(processedArgs)
  25. var globSync = require('glob').sync;
  26. var path = require('path');
  27. const { isMaster } = require('cluster');
  28. var ENV = Object.assign({}, process.env); // Shallow clone it.
  29. var getShellTask = (command, args, options)=>{
  30. return ()=>{
  31. nodeShellExec.apply(null, [command, args, Object.assign({
  32. inherit : true, shell: true, env : ENV, title : `${command} ${args}`
  33. }, options)
  34. ])
  35. }
  36. }
  37. var getPullCmd = (repo)=>{
  38. // console.log(useGitPull)
  39. var pullCmd = [ gitInstallDir
  40. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  41. , { cwd : repo, title : 'pull all origins for ' + repo }]
  42. // var pullCmd = ['pullall', [], { cwd : repo }]
  43. if(useGitPull) pullCmd = ['git', ['pull'], {
  44. inherit : true, shell: true,
  45. cwd : repo
  46. // , env: process.env
  47. , runas : processedArgs.runas
  48. , title : `git pull ${repo}`
  49. }]
  50. return pullCmd
  51. }
  52. var performPull = (repo) => {
  53. if(existsSync(repo)) {
  54. console.log('pulling ' + repo)
  55. return nodeShellExec.apply(null, getPullCmd(repo)).then(()=>{
  56. if(__isElevated) {
  57. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success:true}), {'flag':'a+'} )
  58. }
  59. else statuslog.statuslog(null, repo)
  60. return true;
  61. })
  62. .catch((e)=>{
  63. e.repo = repo;
  64. if(__isElevated) {
  65. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), {'flag':'a+'} )
  66. }
  67. else statuslog.statuslog(e); console.error(e)
  68. })
  69. }
  70. else {
  71. console.log('cloning ' + repo)
  72. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  73. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', defaultRepoServer + `/${defaultRepoOwner}/` + repo + '.git'],
  74. {
  75. inherit : true, shell: true,
  76. env: process.env
  77. , runas : processedArgs.runas
  78. }).catch((e)=>{
  79. throw e;
  80. }).then(()=>{
  81. return nodeShellExec('git', ['config', '--replace-all' , 'core.symlinks', true],
  82. {
  83. inherit : true, shell: true,
  84. env: process.env
  85. , cwd : repo
  86. , runas : processedArgs.runas
  87. , title : `git core.symlinks --replace-all true for ${defaultRepoServer + `/${defaultRepoOwner}/` + repo + '.git'}`
  88. })
  89. .then(()=>{
  90. if(__isElevated) {
  91. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success:true}), {'flag':'a+'} )
  92. }
  93. else statuslog.statuslog(null, repo)
  94. })
  95. .catch((e)=>{
  96. e.repo = repo;
  97. if(__isElevated) {
  98. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), {'flag':'a+'} )
  99. }
  100. else statuslog.statuslog(e);
  101. })
  102. })
  103. .catch(e=>{
  104. e.repo = repo;
  105. if(__isElevated) {
  106. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), {'flag':'a+'} )
  107. }
  108. else statuslog.statuslog(e);
  109. })
  110. }
  111. }
  112. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  113. // -- Currently workaround is to always run from a non-elevated shell.
  114. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  115. var acquireElevationState = ()=>{
  116. if(__isElevated === null) {
  117. return nodeShellExec( "fsutil", ["dirty", "query", "C:"], {
  118. inherit : true
  119. // , shell: true
  120. , stdio: 'ignore'
  121. , env: process.env
  122. , title : `check privileged execution mode using "fsutil dirty query C:"`
  123. }).then((exitcode)=>{
  124. console.log('Elevated')
  125. __isElevated = true;
  126. return true;
  127. }).catch(()=>{
  128. __isElevated = false;
  129. console.log('Not Elevated');
  130. return false;
  131. });
  132. }
  133. else return Promise.resolve(__isElevated);
  134. }
  135. var repomanifest = null;
  136. var currentGitAuthUser ; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current gittea username
  137. var defaultRepoOwner = 'chess';
  138. var elevatedRunasRepos = null
  139. var gitRepos = null
  140. var defaultRepoServer = null
  141. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  142. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  143. var dbForLabel = function(label){
  144. var dbsForLabel = {
  145. devmysql : 'mysql'
  146. , development : 'mssql'
  147. , production : 'mssql'
  148. }
  149. return dbsForLabel[label] || 'mysql'
  150. }
  151. // SAM : TODO Use nodeshellexec where to detect git installation dir
  152. var gitInstallDir = "C:\\Program Files\\Git\\bin\\sh.exe"
  153. // var gitInstallDir = "G:\\Installed\\Git\\bin\\sh.exe"
  154. // Relevant git repos
  155. // var repomanifest = require('../'+repomanifest.instanceName+'-config-'+ nodeenv +'/repo-manifest')()
  156. var exludeMergeRepos = [];
  157. var useGitPull = processedArgs.useGitPull || false;
  158. var configPromise = null
  159. // elxr cli operations
  160. var op = {
  161. 'h' : ()=>{ console.log(elxr.info()); return '-h' }
  162. , 'undefined' : ()=>{ return op.h(); }
  163. , 'reset' : ()=>{
  164. // Reset NPM packages semver so major versions can be updated.
  165. const fs = require('fs')
  166. const wipeDependencies = (__package) => {
  167. const file = fs.readFileSync(__package + '/package.json')
  168. const content = JSON.parse(file)
  169. for (var devDep in content.devDependencies) {
  170. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  171. content.devDependencies[devDep] = '*';
  172. }
  173. }
  174. for (var dep in content.dependencies) {
  175. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  176. content.dependencies[dep] = '*';
  177. }
  178. }
  179. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  180. }
  181. var repos = ['client'];
  182. // repos = gitRepos;
  183. repos.forEach(wipeDependencies)
  184. // if (require.main === module) {
  185. // } else {
  186. // module.exports = wipeDependencies
  187. // }
  188. }
  189. , 'upgrade' : ()=>{
  190. console.log('upgrade.......')
  191. var tasks = [
  192. ()=>{
  193. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  194. inherit : true, shell: true
  195. , env: process.env
  196. }).catch((e)=>{ console.error(e) })
  197. p.position = 1;
  198. console.log('One')
  199. return p;
  200. }
  201. , ()=>{
  202. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  203. inherit : true, shell: true
  204. , env: process.env
  205. }).catch((e)=>{ console.error(e) })
  206. p.position = 2;
  207. console.log('Two')
  208. return p;
  209. }
  210. , ()=>{
  211. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  212. inherit : true, shell: true
  213. , env: process.env
  214. }).catch((e)=>{ console.error(e) })
  215. p.position = 3;
  216. console.log('Three')
  217. return p;
  218. }
  219. , ()=>{
  220. var p = nodeShellExec('n', ['latest'], {
  221. inherit : true, shell: true
  222. , env: process.env
  223. }).catch((e)=>{ console.error(e) })
  224. p.position = 4;
  225. console.log('Four')
  226. return p;
  227. }
  228. ]
  229. any(tasks)
  230. console.log('.......done')
  231. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  232. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  233. console.info('Uninstalling existing ember globally') ;
  234. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  235. stdio: ['pipe', process.stdout, process.stderr],
  236. inherit : true,
  237. shell: true,
  238. cwd : path.dirname(__dirname),
  239. env: env
  240. })
  241. step1.on('close', ()=>{
  242. console.info('Installing ember globally') ;
  243. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  244. stdio: ['pipe', process.stdout, process.stderr],
  245. inherit : true,
  246. shell: true,
  247. cwd : path.dirname(__dirname),
  248. env: env
  249. })
  250. step2.on('close', ()=>{
  251. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  252. stdio: ['pipe', process.stdout, process.stderr],
  253. inherit : true,
  254. shell: true,
  255. cwd : path.dirname(__dirname),
  256. env: env
  257. })
  258. })
  259. })
  260. }
  261. , 'runas' : ()=>{
  262. console.log('Testing Elevation')
  263. if(__isElevated){
  264. try {
  265. op[ processedArgs.label || processedArgs._[0] || 'h']()
  266. }
  267. catch(e){
  268. console.error('Error Invalid command : ' + e)
  269. fs.writeFileSync('run.done', 'error')
  270. }
  271. finally {
  272. }
  273. }
  274. else {
  275. console.log('Requesting Elevated Privileges');
  276. // Wait for the runas to complete before we read it.
  277. try {
  278. fs.unlinkSync('run.done')
  279. fs.unlinkSync('run.log')
  280. }
  281. catch(e) { } //Ignore
  282. // Find node path to send to hta.
  283. return nodeShellExec('where', ['node']).then(r => {
  284. var namedArgs = [];
  285. console.log('result : ' + JSON.stringify(r))
  286. Object.keys(processedArgs).forEach((v)=>{ v!='_' ? namedArgs.push('--'+v+'='+processedArgs[v]) : null; })
  287. // PB : TODO -- Convert all the cli args back to string.
  288. var args = [__dirname + '/windowselevate.hta'].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  289. args.push('--nodepath='+r[r.length-1])
  290. if(!processedArgs.node_env) args.push('--node_env='+ENV.NODE_ENV)
  291. if(processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
  292. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  293. , {
  294. inherit : true
  295. , shell: true
  296. , env: ENV
  297. , runas : 'self'
  298. , title : `runas`
  299. }
  300. ).then(()=>{
  301. // runas returned.
  302. try {
  303. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  304. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags : 'a+'}) + ']');
  305. runaslog.forEach((logEntry)=>{
  306. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry)
  307. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  308. })
  309. }
  310. catch(e){
  311. // We must have a runas log
  312. statuslog.statuslog(e)
  313. console.error('Run log error probably was not created by runas : ' + e)
  314. }
  315. })
  316. .catch(err => console.error('Elevation failed : ' + err));
  317. })
  318. }
  319. }
  320. , 'push' : ()=>{
  321. if(!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  322. // init remote bare from local
  323. // pushandinitremotebare
  324. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  325. // connect to repo server -- net use 172.16.0.27
  326. // cd 172.16.0.27/repos/
  327. // mkdir repo.git
  328. // cd repo.git
  329. // git init --bare
  330. // cd localrepo
  331. // git remote rename origin githubclone
  332. // git remote add origin //172.16.0.27/repos/repo.git
  333. // git push origin master
  334. var repo = processedArgs._[1];
  335. var sequentialTaskShellCommands = [];
  336. if(!existsSync(`Z:/${repo}.git`)){
  337. sequentialTaskShellCommands = [
  338. // ['net', ['use', 'Z:', defaultRepoServer.replace('/','\\')], {
  339. // inherit : true, shell: true
  340. // , env: process.env
  341. // }]
  342. ['pwd', { cwd : 'Z:', inherit : true}]
  343. , ['mkdir', [`${repo}.git`], {
  344. cwd : `Z:`
  345. , inherit : true, shell: true
  346. , env: process.env
  347. }]
  348. , ['pwd', { cwd : `Z:/${repo}.git`, inherit : true}]
  349. , ['git', ['init', '--bare'], { cwd : `Z:/${repo}.git`
  350. , inherit : true, shell: true
  351. , env: process.env
  352. }]
  353. // PB : TODO -- Do this conditionally only...
  354. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd : `${repo}`}, (err)=>{
  355. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  356. } ] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  357. , ['git', ['remote', 'add', 'origin', `${defaultRepoServer}/${repo}.git`], { cwd : `${repo}`}]
  358. // PB : TODO -- If threre is a gitbubclone origin
  359. // Set the master to pull from the local repo.
  360. ]
  361. if(!existsSync(`Z:`)){
  362. sequentialTaskShellCommands.splice(0,0, ['net', ['use', 'Z:', defaultRepoServer.replace(/\//gm,'\\')], {
  363. inherit : true, shell: true
  364. , env: process.env
  365. }])
  366. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  367. // throw 'done'
  368. }
  369. }
  370. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd : `${repo}`}])
  371. // console.dir(sequentialTaskShellCommands);
  372. var tasks = [];
  373. sequentialTaskShellCommands.forEach(shellcmd => {
  374. // console.log(shellcmd)
  375. tasks.push(()=>{
  376. var p = nodeShellExec.apply(null, shellcmd.slice(0,3)).catch((e)=>{ if(shellcmd[3]) { return shellcmd[3]() } else { console.error(e);} })
  377. return p;
  378. })
  379. })
  380. any(tasks);
  381. }
  382. , 'is-git-repo' : (dir)=>{
  383. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio : 'ignore'})
  384. }
  385. , 'set-url' : (remotename, url) => {
  386. var pushable = processedArgs.pushable || false;
  387. remotename = remotename || processedArgs._[1]
  388. url = url || processedArgs._[2]
  389. var serial_perform_git_seturl = (repo)=>{
  390. var options = { cwd : repo }
  391. // console.log(repo)
  392. if(pushable) {
  393. return [
  394. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd : repo }]
  395. ]
  396. }
  397. else {
  398. console.error('not supported for non-pushable')
  399. }
  400. }
  401. var x = (args)=>{
  402. return ()=>{
  403. // console.log(args)
  404. return nodeShellExec.apply(null, args)
  405. }
  406. // return Promise.resolve(true)
  407. }
  408. var perform_git_seturl = (dir)=>{
  409. op['is-git-repo'](dir).then((code)=>{
  410. any( serial_perform_git_seturl(dir.name).map(x) )
  411. }).catch((e)=>{
  412. // console.log('Failed : ' + dir.name)
  413. })
  414. }
  415. const { readdir } = require("fs").promises
  416. const dirs = async (perform, path) => {
  417. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  418. if (dir.isDirectory()) perform(dir)
  419. }
  420. }
  421. dirs( perform_git_seturl)
  422. }
  423. , 'add' : (remotename, url, branch) => {
  424. var pushable = processedArgs.pushable || false;
  425. remotename = remotename || processedArgs._[1]
  426. url = url || processedArgs._[2]
  427. branch = branch || processedArgs._[3]
  428. var serial_perform_git_add = (repo)=>{
  429. var options = { cwd : repo }
  430. // console.log(repo)
  431. if(pushable) {
  432. return [
  433. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd : repo }]
  434. , ['git', ['pull', remotename, branch], { cwd : repo }]
  435. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd : repo }]
  436. ]
  437. }
  438. else {
  439. return [
  440. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd : repo }]
  441. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd : repo }]
  442. , ['git', ['pull', remotename, branch], { cwd : repo }]
  443. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd : repo }]
  444. ]
  445. }
  446. }
  447. var x = (args)=>{
  448. return ()=>{
  449. // console.log(args)
  450. return nodeShellExec.apply(null, args)
  451. }
  452. // return Promise.resolve(true)
  453. }
  454. var perform_git_add = (dir)=>{
  455. op['is-git-repo'](dir).then((code)=>{
  456. // console.log(code)
  457. if(code) {
  458. nodeShellExec('git',['remote', 'get-url', remotename], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  459. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  460. })
  461. .catch((e)=>{
  462. any( serial_perform_git_add(dir.name).map(x) )
  463. })
  464. }
  465. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  466. }).catch((e)=>{
  467. // console.log('Failed : ' + dir.name)
  468. })
  469. }
  470. const { readdir } = require("fs").promises
  471. const dirs = async (perform, path) => {
  472. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  473. if (dir.isDirectory()) perform(dir)
  474. }
  475. }
  476. dirs(perform_git_add)
  477. }
  478. , 'remove' : (remotename) => {
  479. remotename = remotename || processedArgs._[1]
  480. var serial_perform_git_remove = (repo)=>{
  481. var options = { cwd : repo }
  482. // console.log(repo)
  483. return [
  484. ['git', ['remote', 'remove', remotename], { cwd : repo }]
  485. ]
  486. }
  487. var x = (args)=>{
  488. return ()=>{
  489. // console.log(args)
  490. return nodeShellExec.apply(null, args)
  491. }
  492. // return Promise.resolve(true)
  493. }
  494. var perform_git_remove = (dir)=>{
  495. op['is-git-repo'](dir).then((code)=>{
  496. // console.log(code)
  497. if(code) {
  498. nodeShellExec('git',['remote', 'get-url', remotename], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  499. any( serial_perform_git_remove(dir.name).map(x) )
  500. })
  501. .catch((e)=>{
  502. console.log('skipped : ' + dir.name + ', reason : No remote named origin')
  503. })
  504. }
  505. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  506. }).catch((e)=>{
  507. // console.log('Failed : ' + dir.name)
  508. })
  509. }
  510. const { readdir } = require("fs").promises
  511. const dirs = async (perform, path) => {
  512. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  513. if (dir.isDirectory()) perform(dir)
  514. }
  515. }
  516. dirs(perform_git_remove)
  517. }
  518. , 'init-gitea' : (user) => {
  519. user = user || processedArgs._[1]
  520. if(!user) throw 'User name required'
  521. var serial_perform_init_gitea = (repo)=>{
  522. var options = { cwd : repo }
  523. // console.log(repo)
  524. return [
  525. ['git', ['remote', 'add', 'chess', `${defaultRepoServer}/${user}/${repo}.git`], { cwd : repo }]
  526. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd : repo }]
  527. , ['git', ['remote', 'set-url', 'origin', `${defaultRepoServer}/${user}/${repo}.git`], { cwd : repo }]
  528. ]}
  529. var x = (args)=>{
  530. return ()=>{
  531. // console.log(args)
  532. return nodeShellExec.apply(null, args)
  533. }
  534. // return Promise.resolve(true)
  535. }
  536. var perform_init_gitea = (dir)=>{
  537. op['is-git-repo'](dir).then((code)=>{
  538. // console.log(code)
  539. if(code) {
  540. nodeShellExec('git',['remote', 'get-url', 'chess'], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  541. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  542. })
  543. .catch((e)=>{
  544. any( serial_perform_init_gitea(dir.name).map(x) )
  545. })
  546. }
  547. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  548. }).catch((e)=>{
  549. // console.log('Failed : ' + dir.name)
  550. })
  551. }
  552. const { readdir } = require("fs").promises
  553. const dirs = async (perform, path) => {
  554. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  555. if (dir.isDirectory()) perform(dir)
  556. }
  557. }
  558. dirs(perform_init_gitea)
  559. }
  560. , 'syncmaster' : (label) => {
  561. // Usage :
  562. // elxr pull -- Defaults to run config
  563. var env = Object.assign({}, process.env); // Shallow clone it.
  564. // console.dir(env)
  565. console.log('Running exlr pull : ' + path.dirname(__dirname))
  566. if(!processedArgs.runas) gitRepos.forEach(performPull)
  567. if(__isElevated){
  568. return any(elevatedRunasRepos.map((repo)=>performPull(repo))).then(()=>{
  569. fs.writeFileSync('run.done', 'success')
  570. }).catch(()=>{
  571. fs.writeFileSync('run.done', 'error')
  572. })
  573. }
  574. else return op['runas']()
  575. }
  576. , 'pull' : (label) => {
  577. // Usage :
  578. // elxr pull -- Defaults to run config
  579. var env = Object.assign({}, process.env); // Shallow clone it.
  580. console.log('Running exlr pull : ' + path.dirname(__dirname))
  581. var useGitPull = processedArgs.useGitPull || false;
  582. if(__isElevated){
  583. return any(elevatedRunasRepos.map((repo)=>performPull(repo))).then(()=>{
  584. fs.writeFileSync('run.done', 'success')
  585. return true;
  586. }).catch(()=>{
  587. fs.writeFileSync('run.done', 'error')
  588. })
  589. }
  590. else {
  591. // PB : TODO -- Rename op['runas'] to 'elevate'
  592. return op['runas']().then(()=>{ return true; })
  593. .catch((e)=>{
  594. console.error(e)
  595. })
  596. .finally(()=>{
  597. if(!processedArgs.runas) {
  598. var pendingpulls = [];
  599. gitRepos.forEach( (r)=>{ pendingpulls.push(performPull(r)) } )
  600. return Promise.all(pendingpulls).then(results =>{
  601. return true;
  602. }).finally(Traq.finally)
  603. }
  604. })
  605. }
  606. }
  607. , 'isInstalled' : ()=>{
  608. return nodeShellExec('where', [processedArgs._[1]], { inherit : true} ).then(()=>{
  609. console.log(processedArgs._[1] + ' exists.')
  610. return true;
  611. });
  612. }
  613. , 'i' : ()=>{
  614. var tasks = []
  615. tasks.push(op['pull']);
  616. if(!__isElevated){
  617. tasks.push( getShellTask.apply(null, ['rm', ['run.js']] ) )
  618. tasks.push(op['use'])
  619. tasks.push(op['npmi'])
  620. }
  621. // var tasksdefs = [
  622. // ['elxr', ['pull']]
  623. // , ['elxr', ['use', 'elixir']]
  624. // , ['elxr', ['npmi']]
  625. // ]
  626. // tasksdefs.forEach(tasksdef=>{
  627. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  628. // })
  629. return any(tasks);
  630. }
  631. , 'npmi' : ()=>{
  632. var tasks = [];
  633. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  634. npmbuildrepos.forEach(repo => {
  635. tasks.push(()=>{
  636. return nodeShellExec('npm', ['i --force'], {
  637. inherit : true, shell: true
  638. , cwd : repo
  639. , env: process.env
  640. , title : `npm i for ${repo}`
  641. }).catch((e)=>{
  642. console.error('Ignoring Benign Error'); console.error(e);
  643. }).then(()=>{
  644. console.log(`--------------------npm run build for ${repo}--------------------`)
  645. return nodeShellExec('npm', ['run build'], {
  646. inherit : true, shell: true
  647. , cwd : repo
  648. , env: process.env
  649. , title : `npm run build for ${repo}`
  650. }).then(Tasq.then).catch(Tasq.catch)
  651. })
  652. })
  653. })
  654. any(tasks).then(()=>{
  655. gitRepos.push('client/server');
  656. gitRepos = gitRepos.concat(elevatedRunasRepos);
  657. var rmtasks = []
  658. var repotasks = []
  659. gitRepos.forEach(repo => {
  660. rmtasks.push(()=>{
  661. console.log(`--------------------rm package-lock.json for ${repo}--------------------`)
  662. return nodeShellExec('rm', ['package-lock.json'], {
  663. inherit : true, shell: true
  664. , cwd : repo
  665. , env: process.env
  666. , title : `rm 'package-lock.json' for ${repo}`
  667. }).catch((e)=>{console.error(e)})
  668. })
  669. if( npmbuildrepos.indexOf(repo) < 0) {
  670. repotasks.push(
  671. ()=>{
  672. console.log(`--------------------npm i for ${repo}--------------------`)
  673. var p = nodeShellExec('npm', ['i --force'], {
  674. inherit : true, shell: true
  675. , cwd : repo
  676. , env: process.env
  677. , title : `npm i for ${repo}`
  678. }).then(Tasq.then).catch(Tasq.catch)
  679. return p;
  680. })
  681. }
  682. })
  683. var bowerRepos = ['client']
  684. bowerRepos.forEach(repo => {
  685. repotasks.push(()=>{
  686. var p = nodeShellExec('bower', ['install'], {
  687. inherit : true, shell: true
  688. , cwd : repo
  689. , env: process.env
  690. , title : `bower i for ${repo}`
  691. }).then(Tasq.then).catch(Tasq.catch)
  692. return p;
  693. })
  694. })
  695. return Promise.all(rmtasks).then(()=>any(repotasks));
  696. }).catch(e=>{
  697. }).finally(statuslog.finally)
  698. }
  699. , 'start' : (label)=>{
  700. console.log('Starting Elixir Server.');
  701. var env = Object.assign({}, process.env); // Shallow clone it.
  702. // console.dir(env)
  703. env.NODE_ENV = process.env.NODE_ENV || 'development';
  704. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  705. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  706. // cmd = 'node'
  707. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
  708. var childPromise = nodeShellExec(...cmd, {
  709. // inherit : true,
  710. shell: true,
  711. detached: true,
  712. stdio: 'ignore',
  713. cwd : 'elixir-server'
  714. , env: env
  715. })
  716. var child = childPromise.process;
  717. if (typeof child.pid !== 'undefined') {
  718. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  719. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  720. encoding: 'utf8'
  721. })
  722. }
  723. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  724. // inherit : true,
  725. // shell: true, detached: true,
  726. // cwd : 'qms/server',
  727. // env: env,
  728. // shell : true
  729. // })
  730. // nodeShellExec('ember', ['s'], {
  731. // // inherit : true,
  732. // shell: true, detached: true,
  733. // cwd : 'client/',
  734. // env: env
  735. // })
  736. console.log('Starting Elixir Client Host.');
  737. var cmd = ['ember', ['s']]
  738. var childPromise = nodeShellExec(...cmd, {
  739. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  740. // PB : TODO -- ember debugging.
  741. // inherit : true,
  742. shell: true,
  743. detached: true,
  744. stdio: 'ignore',
  745. cwd : 'client'
  746. , env: env
  747. })
  748. // .catch(e=>console.error(e))
  749. child = childPromise.process;
  750. if (typeof child.pid !== 'undefined') {
  751. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  752. fs.writeFileSync('.client.server.pid', child.pid, {
  753. encoding: 'utf8'
  754. })
  755. }
  756. }
  757. , 'stop' : (label)=>{
  758. const kill = require('tree-kill');
  759. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  760. encoding: 'utf8'
  761. })
  762. fs.unlinkSync('.elixir-server.elixir.server.pid')
  763. console.log(serverPid)
  764. kill(serverPid)
  765. serverPid = fs.readFileSync('.client.server.pid', {
  766. encoding: 'utf8'
  767. })
  768. fs.unlinkSync('.client.server.pid')
  769. console.log(serverPid)
  770. kill(serverPid)
  771. }
  772. , 'use' : ()=>{
  773. // use a certain named instance.
  774. // Eg :
  775. // 1) elxr use elixir
  776. // 2) elxr use cihsr
  777. // If environment is not specified defaults to development.
  778. // 1) NODE=test elxr use elixir
  779. /*// Steps
  780. 1) Delete Config and Data symlinks
  781. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  782. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  783. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  784. 5) Iterates all repos and merge from source configured in mergeSource. 'git', ['merge', mergeSource],
  785. */
  786. var runconfig = { NODE_ENV : repomanifest.node_env }
  787. try { runconfig = Object.assign(runconfig, require('../run.js')) } catch(e) { }
  788. if((!processedArgs.runas || processedArgs.runas !== 'self') &&
  789. runconfig.NODE_ENV && runconfig.NODE_ENV === (repomanifest.node_env || runconfig.NODE_ENV) &&
  790. repomanifest.instanceName && runconfig.use === repomanifest.instanceName) {
  791. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  792. if(processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  793. return
  794. }
  795. var tasks = [
  796. ()=>{
  797. if(existsSync('config')) {
  798. var p = nodeShellExec('rmdir', ['config'], {inherit : true, shell: true, env: process.env }
  799. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  800. return p;
  801. }
  802. else return Promise.resolve(true);
  803. },
  804. ()=>{
  805. if(existsSync('data')) {
  806. var p = nodeShellExec('rmdir', ['data'], { inherit : true, shell: true, env: process.env }
  807. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  808. return p;
  809. }
  810. else return Promise.resolve(true);
  811. },
  812. ];
  813. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  814. if(processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  815. if(!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  816. // console.log(process.env.cwd)
  817. fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
  818. var checkoutMap = {
  819. 'development' : 'master',
  820. }
  821. // cant use git checkout -b it fails with branch already exists.
  822. var performCheckout = (repo, branch)=>{
  823. if(!branch) return Promise.resolve({ 'skipped' : true })
  824. if(excludeCheckouts[repo]) return Promise.resolve({ 'skipped' : true })
  825. return nodeShellExec('git', ['checkout', branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  826. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  827. // inherit : true, shell: true,
  828. cwd : repo
  829. // , stdio : ignore // Use when we want to silcence output completely.
  830. , runas : processedArgs.runas
  831. , title : `git checkout ${branch ||checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${repo}`
  832. }).catch((e)=>{ console.error(e); return { error : true, message : repo} })
  833. }
  834. if(runconfig.NODE_ENV === 'development') performCheckout = ()=>{ return Promise.resolve(true) }
  835. var performPullAll = (repo)=>{
  836. if(excludeCheckouts[repo]) return Promise.resolve({ 'skipped' : true })
  837. return nodeShellExec('git', ['pull', '--all'], {
  838. // inherit : true, shell: true,
  839. cwd : repo
  840. , runas : processedArgs.runas
  841. , title : `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${repo}`
  842. }).catch((e)=>{ console.error(e); return { error : true, message : repo} })
  843. }
  844. var mergeSources = {
  845. 'development' : null,
  846. 'test' : 'master',
  847. 'production' : 'master'
  848. }
  849. var excludeCheckouts = Object.assign(exludeMergeRepos)
  850. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  851. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  852. var mergeSource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  853. var performMerge = (repo)=>{
  854. if(exludeMergeRepos[repo]) return Promise.resolve({ 'skipped' : true })
  855. return nodeShellExec('git', ['merge', mergeSource], {
  856. inherit : true, shell: true,
  857. cwd : repo
  858. , runas : processedArgs.runas
  859. }).catch((e)=>{ console.error(e) })
  860. }
  861. if(runconfig.NODE_ENV === 'development') performMerge = ()=>{ return Promise.resolve(true) }
  862. any(tasks).then(()=>{
  863. if(!processedArgs.runas) return op['runas']()
  864. tasks = [
  865. ()=>{
  866. // Use junctions to avoid npm package issues
  867. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV ], {
  868. inherit : true, shell: true
  869. , env: process.env
  870. }).catch((e)=>{ console.error(e) })
  871. return p;
  872. }
  873. ];
  874. if(processedArgs._[1]) {
  875. tasks = tasks.concat(
  876. [
  877. ()=>{
  878. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  879. inherit : true, shell: true
  880. , env: process.env
  881. }).catch((e)=>{ console.error(e) })
  882. return p;
  883. }
  884. ]
  885. )
  886. }
  887. return any(tasks)
  888. //target is the env is we specify in elxr use command. Default is dev
  889. .then( //Switch to target branch
  890. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))
  891. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))]) )
  892. .then( //PULL from target branch
  893. () => any([ any(gitRepos.map((repo)=>performPullAll(repo))), any(elevatedRunasRepos.map((repo)=>performPullAll(repo)))]) )
  894. .then( //Switch to merge source branch
  895. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'] )))
  896. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'])))]) )
  897. .then( //Pull on merge source branch
  898. () => any([ any(gitRepos.map((repo)=>performPullAll(repo))), any(elevatedRunasRepos.map((repo)=>performPullAll(repo)))]) )
  899. .then( //Switch to target branch
  900. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))
  901. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))]) )
  902. .then( //Merge source branch to target branch
  903. () => any([ any(gitRepos.map((repo)=>performMerge(repo))).catch(err=>{ console.error('error in performMerge ' + err)}) ,
  904. any(elevatedRunasRepos.map((repo)=>performMerge(repo))).catch(err=>{ console.error('error in performMerge ' + err)})]) )
  905. .then( () => {
  906. // Move test config from dev.
  907. // if(process.env.NODE_ENV === 'test'){
  908. // var devcfgreponame = runconfig.use + '-config' + '-development';
  909. // var testcfgreponame = runconfig.use + '-config' + '-test';
  910. // var testcfgdir = path.dirname(__dirname) + '/' + testcfgreponame + '/'
  911. // var devcfgdir = path.dirname(__dirname) + '/' + devcfgreponame + '/' //eg (elxr/../elixir-config.development)
  912. // return any([
  913. // ()=>{
  914. // return nodeShellExec('git', ['checkout', 'test'], {
  915. // inherit : true, shell: true,
  916. // cwd : testcfgdir
  917. // // , env: process.env
  918. // , runas : processedArgs.runas
  919. // , title : `git checkout test for ${testcfgreponame}`
  920. // }).catch((e)=>{ console.error(e) })
  921. // }
  922. // , ()=> {
  923. // return nodeShellExec('git', ['checkout', 'master'], {
  924. // inherit : true, shell: true,
  925. // cwd : devcfgdir
  926. // // , env: process.env
  927. // , runas : processedArgs.runas
  928. // , title : `git checkout master for ${devcfgreponame}`
  929. // }).catch((e)=>{ console.error(e) })
  930. // }
  931. // , ()=> {
  932. // globSync( '**/*.test.js', {cwd : devcfgdir}).map((filename) => {
  933. // console.log('File found : ' + devcfgdir + filename)
  934. // fs.copyFileSync(devcfgdir + filename, testcfgdir+ filename);
  935. // })
  936. // return nodeShellExec('git', ['checkout', 'test'], {
  937. // inherit : true, shell: true,
  938. // cwd : devcfgdir
  939. // // , env: process.env
  940. // , runas : processedArgs.runas
  941. // , title : `git checkout test for ${devcfgreponame}`
  942. // }).catch((e)=>{ console.error(e) })
  943. // }
  944. // ])
  945. // }
  946. // else {
  947. return Promise.resolve(true)
  948. // }
  949. })
  950. .then(()=>{
  951. fs.writeFileSync('run.done', 'success')
  952. }).catch(()=>{
  953. fs.writeFileSync('run.done', 'error')
  954. })
  955. }).catch(()=>{
  956. fs.writeFileSync('run.done', 'error')
  957. })
  958. // Antibiotic stewardship program.
  959. // 1st use is fine.
  960. // Max vials dispense
  961. // 2nd use Pharmacy needs justification Form.
  962. // Approval after a certain period of time.
  963. }
  964. , 'g' : ()=>{
  965. if(processedArgs.h) {
  966. console.log('elxr g [modelname] => generate a model named [modelname]');
  967. console.log('elxr g => regenerate all known models');
  968. return
  969. }
  970. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  971. // console.log('Starting directory: ' + process.cwd());
  972. // try {
  973. // child = child.on('close', () => { process.chdir(label) } );
  974. // console.log('New directory: ' + process.cwd());
  975. // }
  976. // catch (err) {
  977. // console.log('chdir: ' + err);
  978. // }
  979. // child.on('close', function(){
  980. // var options = {
  981. // shell : true
  982. // , inherit : true
  983. // // , cwd : '' + process.cwd
  984. // // , env : process.env
  985. // };
  986. // nodeShellExec('git', ['init'], { inherit : true});
  987. if(0){
  988. // PB : TODO -- Special google chrome profile for tests etc.
  989. nodeShellExec('pwd', { inherit : true});
  990. // /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"
  991. // "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
  992. // "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
  993. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  994. "--profile-directory=Profile 1"
  995. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  996. }
  997. // nodeShellExec('npm', ['init', '-y'], options);
  998. // nodeShellExec('npm', ['init', '-y'], options);
  999. // })
  1000. var g = {
  1001. 'client' : ()=>{
  1002. console.info('Creating new ember client named : ' + processedArgs._[2] ) ;
  1003. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1004. stdio: ['pipe', process.stdout, process.stderr],
  1005. inherit : true,
  1006. shell: true,
  1007. cwd : path.dirname(__dirname),
  1008. env: env
  1009. })
  1010. },
  1011. 'modelr' : ()=>{
  1012. var tasks = [
  1013. ()=>{
  1014. var p = nodeShellExec('"ember"', [
  1015. 'g'
  1016. , 'modelr'
  1017. , processedArgs._[2]], {
  1018. inherit : true, shell: true, env: process.env
  1019. }).then(()=>{
  1020. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  1021. return true;
  1022. }).catch((e)=>{ console.error(e) })
  1023. return p;
  1024. },
  1025. ()=>{
  1026. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1027. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  1028. chromeprefs = JSON.parse(chromeprefs)
  1029. var previous = chromeprefs.download.default_directory;
  1030. var parentDir = path.dirname(__dirname);
  1031. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1032. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1033. // PB : TODO -- detect where chrome is installed.
  1034. // PB : TODO -- set the download dir to the place where files are needed.
  1035. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1036. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1037. , '--profile-directory="chess"'
  1038. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1039. inherit : true, shell: true
  1040. , env: process.env
  1041. }).then(()=>{
  1042. chromeprefs.download.default_directory = previous;
  1043. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1044. return true;
  1045. }).catch((e)=>{ console.error(e) })
  1046. return p;
  1047. }
  1048. ,
  1049. ()=>{
  1050. console.log('Browser process should have closed here....')
  1051. return true;
  1052. }
  1053. ]
  1054. any(tasks)
  1055. }
  1056. }
  1057. g[processedArgs._[1]]();
  1058. }
  1059. }
  1060. var util = require('util')
  1061. var cliname = 'elxr';
  1062. var ver = '1.1';
  1063. var help = `# list of commands... please refer dveloper documentation for ${cliname}
  1064. ${
  1065. // util.inspect(
  1066. [Object.keys(op)]
  1067. // )
  1068. }
  1069. `;
  1070. var elxr = {
  1071. help(){
  1072. return chalk.cyanBright(`
  1073. -------------------------------------------------------------------------------
  1074. *** BBH Elixir ***
  1075. -------------------------------------------------------------------------------
  1076. elxr ${ver}
  1077. A cli tool for chess
  1078. ${help}
  1079. -------------------------------------------------------------------------------
  1080. `)}
  1081. , info(){
  1082. return chalk.cyanBright(`
  1083. -------------------------------------------------------------------------------
  1084. *** BBH Elixir ***
  1085. -------------------------------------------------------------------------------
  1086. elxr ${ver}
  1087. A cli tool for chess
  1088. -------------------------------------------------------------------------------
  1089. `)}
  1090. }
  1091. // The main elxr cli process
  1092. function elxrworker(hasconfig){
  1093. defaultRepoServer = repomanifest.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  1094. ENV.NODE_ENV = repomanifest.node_env;
  1095. return acquireElevationState().then(()=>{
  1096. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  1097. gitRepos = repomanifest.repos
  1098. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  1099. elevatedRunasRepos = repomanifest.elevated
  1100. // Repos that should excluded from merge for releases...
  1101. exludeMergeRepos = repomanifest.exludeMergeRepos
  1102. var env = Object.assign({}, process.env); // Shallow clone it.
  1103. var __runcmd = function(label){
  1104. return op[label] ? op[label]() : null;
  1105. }
  1106. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  1107. // mysql -u root -p db_name < drop_all_tables.sql
  1108. var mysql = '../xampp/mysql/bin/mysql'
  1109. var mysqldump = '../xampp/mysql/bin/mysqldump'
  1110. // --runas
  1111. if(processedArgs.runas) {
  1112. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  1113. __runcmd('runas')
  1114. }
  1115. else __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  1116. })
  1117. }
  1118. var getManifest = function(){
  1119. // Once choices are made we need to load config according to those choices.
  1120. // No trace of a previous run...
  1121. // Default Config...
  1122. return repomanifest = {
  1123. // Default is public server only.
  1124. reposervers : [ 'https://git.bbh.org.in' ]
  1125. // All public repos are by default available.
  1126. , repos : [
  1127. 'setup'
  1128. , 'elxr'
  1129. , 'loopback-connector-mysql'
  1130. , 'loopback-jsonapi-model-serializer'
  1131. , 'loopback-component-jsonapi'
  1132. , 'ember-service-worker'
  1133. , 'ember-service-worker-asset-cache'
  1134. , 'ember-service-worker-cache-fallback'
  1135. , 'ember-service-worker-index'
  1136. , 'ember-sw-client-route'
  1137. ]
  1138. , elevated : [ ]
  1139. , exludeMergeRepos : {}
  1140. , instanceName : processedArgs._[1] || 'chess'
  1141. // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
  1142. , node_env : (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  1143. };
  1144. }
  1145. function acquireChoices(){
  1146. var hasconfig = false;
  1147. console.warn(chalk.yellow(`
  1148. -------------------------------------------------------------------------------
  1149. Warning : Cannot locate your preferred configuration since it was not specified
  1150. You should fork the default chess configuration to customize and make it
  1151. your own instance with a named config as
  1152. {{yourowninstancename}}-config-{{yourcurrentenvironment}}
  1153. And then run this tool as follows
  1154. NODE_ENV={{yourenvironment}} elxr i {{yourowninstancename}}
  1155. OR
  1156. Run this tool with the following command to use a quick start default.
  1157. node elxr --default
  1158. OR
  1159. Choose the the option to create a new instance for you interactively.
  1160. We will run your choice of default or create your own at the next prompt.
  1161. -------------------------------------------------------------------------------
  1162. `))
  1163. var prompt = cli.prompt;
  1164. return prompt.ask(`Choose an option :
  1165. d) Install the default chess instance.
  1166. => elxr i chess node_env=development --default
  1167. n) Create your custom new instance interactively
  1168. => elxr i {{instanceName}} node_env={{environment}}
  1169. i) Choose an instance and environment to install
  1170. => elxr i {{instanceName}} node_env={{environment}}
  1171. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  1172. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  1173. h) Help
  1174. q) Quit
  1175. Default <= d
  1176. : `).then((choice)=>{
  1177. prompt.close();
  1178. if(choice && choice==='d' || !choice) {
  1179. processedArgs._[0] = 'i'
  1180. processedArgs._[1] = processedArgs._[1] || 'chess'
  1181. processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  1182. getManifest()
  1183. }
  1184. else if(choice === 'h'){ processedArgs._[0] = 'h'
  1185. fs.writeFileSync('run.done', 'noop help');
  1186. console.log(elxr.help()); process.exit()
  1187. }
  1188. else if(choice === 'n' || choice === 'i'){
  1189. var p1 = cli.prompt;
  1190. return p1.ask(`Enter Instance Name ( <= elixir ) : `).then(function(instanceName){
  1191. processedArgs._[0] = 'i'
  1192. processedArgs._[1] = instanceName ? instanceName : 'elixir'
  1193. return p1.ask(`Enter Environment ( <= development ) : `).then(function(node_env){
  1194. p1.close()
  1195. processedArgs.node_env = node_env ? node_env : 'development'
  1196. if(choice === 'n') {
  1197. console.warn(
  1198. chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  1199. process.exit();
  1200. }
  1201. })
  1202. })
  1203. } else if(choice === 'c'){
  1204. var p1 = cli.prompt;
  1205. return p1.ask(`Enter Instance Name ( <= elixir ) : `).then(function(instanceName){
  1206. processedArgs._[1] = instanceName ? instanceName : 'elixir'
  1207. return p1.ask(`Enter Environment ( <= development ) : `).then(function(node_env){
  1208. processedArgs.node_env = node_env ? node_env : 'development'
  1209. return p1.ask(`Enter cmd :
  1210. p) pull
  1211. Default <= p
  1212. : `).then(function(cmd){
  1213. if(!cmd || cmd === 'p') {
  1214. processedArgs._[0] = 'pull'
  1215. }
  1216. else processedArgs._[0] = cmd
  1217. p1.close()
  1218. })
  1219. })
  1220. })
  1221. } else {
  1222. 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.`));
  1223. fs.writeFileSync('run.log', ', ' + JSON.stringify({ success : 'quit without execution' }), {'flag':'a+'} )
  1224. fs.writeFileSync('run.done', 'noop quit');
  1225. process.exit()
  1226. }
  1227. })
  1228. }
  1229. var acquireConfig = function(){
  1230. var configrepo = processedArgs._[1]+'-config-'+processedArgs.node_env;
  1231. return performPull(configrepo).then(()=>{
  1232. var manifestpath = '../'+processedArgs._[1]+'-config-'+processedArgs.node_env+'/repo-manifest';
  1233. repomanifest = require(manifestpath)()
  1234. var chessinstances = {}
  1235. try {
  1236. chessinstances = require('../chessinstances.js');
  1237. chessinstances[processedArgs._[1]][processedArgs.node_env] = repomanifest;
  1238. }
  1239. catch(e) {
  1240. chessinstances[processedArgs._[1]] = {}
  1241. chessinstances[processedArgs._[1]][processedArgs.node_env] = repomanifest;
  1242. }
  1243. chessinstances['current_run'] = { instanceName : processedArgs._[1], node_env : processedArgs.node_env }
  1244. fs.writeFileSync('chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances) + '', {'flag':'w'} )
  1245. })
  1246. .catch(()=>{
  1247. console.error('Config acquisition failed.')
  1248. })
  1249. }
  1250. try {
  1251. var chessinstances = require('../chessinstances.js');
  1252. processedArgs._[1] = chessinstances.current_run.instanceName;
  1253. processedArgs.node_env = chessinstances.current_run.node_env;
  1254. repomanifest = chessinstances[chessinstances.current_run.instanceName][chessinstances.current_run.node_env]
  1255. return acquireConfig().catch((e)=>{
  1256. console.error('Exisitng config Failed. Fix config and rerun or chose another.')
  1257. console.error(e);
  1258. }).then(()=>{ return elxrworker(true) })
  1259. }
  1260. catch(e) {
  1261. return acquireChoices().then(()=>{
  1262. return acquireConfig().catch((e)=>{
  1263. console.error('Chosen cofiguraton failed or not found')
  1264. console.error(e)
  1265. fs.writeFileSync('run.log', ', ' + JSON.stringify({ error : e.message }), {'flag':'a+'} )
  1266. fs.writeFileSync('run.done', 'error');
  1267. return process.exit()
  1268. })
  1269. .then(()=>{ return elxrworker(true) })
  1270. })
  1271. }