You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 55KB

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