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

index.js 46KB

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