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.

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