您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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