選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

index.js 53KB

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