555
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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