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.

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