您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

5 年前
5 年前
5 年前
5 年前
5 年前
5 年前
5 年前
5 年前
5 年前
5 年前
5 年前
5 年前
5 年前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. 
  2. // --------------
  3. // elxr
  4. // A cli tool for elixr.
  5. const { existsSync } = require('fs');
  6. const fs = require('fs')
  7. const { spawn, spawnSync } = require('child_process');
  8. const cliargs = require('../elxr/cliargs'); // Use minimist...
  9. const processedArgs = cliargs(process.argv.slice(2));
  10. console.dir(processedArgs)
  11. var path = require('path')
  12. // Serialize a set of functions that will execute to return a promises one after the other.
  13. // Will stop when any one fails.
  14. function any(iterable, continueOnFailure) {
  15. return iterable.reduce(
  16. (p, fn, i ,a) => {
  17. // console.log('accumulator :');
  18. // console.log(p);
  19. if(Promise.resolve(p) === p ) {
  20. return p.then((pVal) => {
  21. if(Promise.resolve(pVal) === pVal) {
  22. // Passed in function retured a promise. We still need to wait for it.
  23. pVal.then((pVal)=>{
  24. // console.log('Then --pVal = ' + pVal + ' bContinue = ' + continueOnFailure ); console.log(p);
  25. if(!pVal && !continueOnFailure) {
  26. console.error("E : pVal :" + pVal);
  27. // i==0 ? null : console.error("E :1 a[i-1] " + a[i-1]);
  28. // a.map((i)=>console.error(i.toString()));
  29. console.error('debugData 3 -------------------');
  30. // console.error(debugData);
  31. console.error('debugData 3 -------------------');
  32. console.log("Cancelling remaining...");
  33. throw 'Failed in reduce 1 '
  34. return false;
  35. }
  36. // console.log('calling fn : '+ fn);
  37. return (Promise.resolve(fn) === fn ) ? fn : fn() ;
  38. })
  39. }
  40. else {
  41. // console.log('Then --pVal = ' + pVal + ' bContinue = ' + continueOnFailure ); console.log(p);
  42. if(!pVal && !continueOnFailure) {
  43. console.error("E : pVal :" + pVal);
  44. // i==0 ? null : console.error("E :1 a[i-1] " + a[i-1]);
  45. // a.map((i)=>console.error(i.toString()));
  46. console.error('debugData 3 -------------------');
  47. // console.error(debugData);
  48. console.error('debugData 3 -------------------');
  49. console.log("Cancelling remaining...");
  50. throw 'Failed in reduce 1 '
  51. return false;
  52. }
  53. // console.log('calling fn : '+ fn);
  54. return (Promise.resolve(fn) === fn ) ? fn : fn() ;
  55. }
  56. }).catch((error) => {
  57. console.error("E : " + error);
  58. fn ? console.error("Fn : " + fn.toString()) : null;
  59. // i==0 ? null : console.error("E :2 a[i-1] " + a[i-1]);
  60. // a.map((i)=>console.error(i.toString()));
  61. console.error('debugData 4-------------------------');
  62. // console.error(debugData);
  63. console.error('debugData 4-------------------------');
  64. throw 'Failed in reduce 2 '
  65. return false;
  66. })
  67. }
  68. else if(!p) {
  69. console.log("Bypass on failure");
  70. return false;
  71. }
  72. }
  73. , Promise.resolve(true)
  74. );
  75. }
  76. var __isElevated = null;
  77. var isRunningElevated = ()=>{
  78. if(__isElevated === null) {
  79. return nodeShellExec( "fsutil", ["dirty", "query", "C:"], {
  80. inherit : true
  81. // , shell: true
  82. // , stdio: 'ignore'
  83. , env: process.env
  84. , title : `check privileged execution mode using "fsutil dirty query C:"`
  85. }).then((exitcode)=>{
  86. console.log('Elevated')
  87. __isElevated = true;
  88. return true;
  89. }).catch(()=>{
  90. __isElevated = false;
  91. console.log('Not Elevated');
  92. throw false;
  93. });
  94. }
  95. else return Promise.resolve(__isElevated);
  96. }
  97. var cli = 'elxr';
  98. var ver = '#unversioned';
  99. var help = '#unkown list of commands... please refer dveloper documentation for ' + cli;
  100. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  101. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  102. var dbForLabel = function(label){
  103. var dbsForLabel = {
  104. devmysql : 'mysql'
  105. , development : 'mssql'
  106. , production : 'mssql'
  107. }
  108. return dbsForLabel[label] || 'mysql'
  109. }
  110. // Relevant git repos
  111. var gitRepos = [
  112. 'ember-masonry-grid'
  113. , 'bbhverse'
  114. , 'clientverse'
  115. , 'serververse'
  116. , 'client'
  117. // , 'client/server'
  118. , 'elxr'
  119. , 'elixir-client'
  120. , 'elixir-client-unlinked'
  121. , 'ember-searchable-select'
  122. , 'loopback-component-jsonapi'
  123. , 'elixir-config-development'
  124. , 'cihsr-config'
  125. , 'cihsr-data'
  126. , 'elixir-data'
  127. , 'loopback-connector-ds'
  128. , 'chess-server-lib'
  129. , 'setup'
  130. ]
  131. // Repositiories that have symlinks that required elevated priviletes in windows to create symlinks
  132. //
  133. var elevatedRunasRepos = [
  134. 'elixir-server'
  135. , 'cihsr-server'
  136. , 'chess-server'
  137. ]
  138. var productionRepos = [
  139. 'elixir-config-production'
  140. ]
  141. var env = Object.assign({}, process.env); // Shallow clone it.
  142. var __runcmd = function(label){
  143. var op = {
  144. 'h' : ()=>{ console.log(cli + ' ' + ver + ' ' + help); return '-h' }
  145. , 'undefined' : ()=>{ return op.h(); }
  146. , 'upgrade' : ()=>{
  147. console.log('upgrade.......')
  148. var tasks = [
  149. ()=>{
  150. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  151. inherit : true, shell: true
  152. , env: process.env
  153. }).catch((e)=>{ console.error(e) })
  154. p.position = 1;
  155. console.log('One')
  156. return p;
  157. }
  158. , ()=>{
  159. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  160. inherit : true, shell: true
  161. , env: process.env
  162. }).catch((e)=>{ console.error(e) })
  163. p.position = 2;
  164. console.log('Two')
  165. return p;
  166. }
  167. , ()=>{
  168. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  169. inherit : true, shell: true
  170. , env: process.env
  171. }).catch((e)=>{ console.error(e) })
  172. p.position = 3;
  173. console.log('Three')
  174. return p;
  175. }
  176. , ()=>{
  177. var p = nodeShellExec('n', ['latest'], {
  178. inherit : true, shell: true
  179. , env: process.env
  180. }).catch((e)=>{ console.error(e) })
  181. p.position = 4;
  182. console.log('Four')
  183. return p;
  184. }
  185. ]
  186. any(tasks)
  187. console.log('.......done')
  188. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  189. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  190. console.info('Uninstalling existing ember globally') ;
  191. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  192. stdio: ['pipe', process.stdout, process.stderr],
  193. inherit : true,
  194. shell: true,
  195. cwd : path.dirname(__dirname),
  196. env: env
  197. })
  198. step1.on('close', ()=>{
  199. console.info('Installing ember globally') ;
  200. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  201. stdio: ['pipe', process.stdout, process.stderr],
  202. inherit : true,
  203. shell: true,
  204. cwd : path.dirname(__dirname),
  205. env: env
  206. })
  207. step2.on('close', ()=>{
  208. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  209. stdio: ['pipe', process.stdout, process.stderr],
  210. inherit : true,
  211. shell: true,
  212. cwd : path.dirname(__dirname),
  213. env: env
  214. })
  215. })
  216. })
  217. }
  218. , 'runas' : ()=>{
  219. return isRunningElevated().then(
  220. (isElevated) => {
  221. if(isElevated) {
  222. try {
  223. op[ processedArgs.label || processedArgs._[0] || 'h']()
  224. }
  225. catch(e){
  226. console.error('Error Invalid command : ' + e)
  227. fs.writeFileSync('run.done', 'success')
  228. }
  229. finally {
  230. }
  231. } else throw false;
  232. }
  233. )
  234. .catch(()=>{
  235. console.log('Not Elevated Requesting Elevated Privileges');
  236. // Wait for the runas to complete before we read it.
  237. try {
  238. fs.unlinkSync('run.done')
  239. fs.unlinkSync('run.log')
  240. }
  241. catch(e) { } //Ignore
  242. var args = [__dirname + '/windowselevate.hta'].concat(processedArgs._); args.push('--runas')
  243. nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  244. , {
  245. inherit : true
  246. ,
  247. shell: true
  248. // ,
  249. , env: process.env
  250. , runas : true
  251. , title : `runas`
  252. }
  253. ).then(()=>{
  254. // runas returned.
  255. var runaslog = JSON.parse('[ { "success" : true, "result" : "runas Log" }' + fs.readFileSync('run.log', { flags : 'a+'}) + ']');
  256. runaslog.forEach((logEntry)=>{
  257. logEntry.succes ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' '))
  258. })
  259. })
  260. .catch(err => console.error('Elevation failed : ' + err));
  261. })
  262. }
  263. , 'push' : ()=>{
  264. if(!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  265. // init remote bare from local
  266. // pushandinitremotebare
  267. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  268. // connect to repo server -- net use 172.16.0.27
  269. // cd 172.16.0.27/repos/
  270. // mkdir repo.git
  271. // cd repo.git
  272. // git init --bare
  273. // cd localrepo
  274. // git remote rename origin githubclone
  275. // git remote add origin //172.16.0.27/repos/repo.git
  276. // git push origin master
  277. var repo = processedArgs._[1];
  278. var defaultRepoServer = '//172.16.0.27/repos'
  279. var sequentialTaskShellCommands = [];
  280. if(!existsSync(`Z:/${repo}.git`)){
  281. sequentialTaskShellCommands = [
  282. // ['net', ['use', 'Z:', defaultRepoServer.replace('/','\\')], {
  283. // inherit : true, shell: true
  284. // , env: process.env
  285. // }]
  286. ['pwd', { cwd : 'Z:', inherit : true}]
  287. , ['mkdir', [`${repo}.git`], {
  288. cwd : `Z:`
  289. , inherit : true, shell: true
  290. , env: process.env
  291. }]
  292. , ['pwd', { cwd : `Z:/${repo}.git`, inherit : true}]
  293. , ['git', ['init', '--bare'], { cwd : `Z:/${repo}.git`
  294. , inherit : true, shell: true
  295. , env: process.env
  296. }]
  297. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd : `${repo}`}, (err)=>{
  298. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  299. } ] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  300. , ['git', ['remote', 'add', 'origin', `${defaultRepoServer}/${repo}.git`], { cwd : `${repo}`}]
  301. ]
  302. if(!existsSync(`Z:`)){
  303. sequentialTaskShellCommands.splice(0,0, ['net', ['use', 'Z:', defaultRepoServer.replace(/\//gm,'\\')], {
  304. inherit : true, shell: true
  305. , env: process.env
  306. }])
  307. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  308. // throw 'done'
  309. }
  310. }
  311. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd : `${repo}`}])
  312. // console.dir(sequentialTaskShellCommands);
  313. var tasks = [];
  314. sequentialTaskShellCommands.forEach(shellcmd => {
  315. // console.log(shellcmd)
  316. tasks.push(()=>{
  317. var p = nodeShellExec.apply(null, shellcmd.slice(0,3)).catch((e)=>{ if(shellcmd[3]) { return shellcmd[3]() } else { console.error(e);} })
  318. return p;
  319. })
  320. })
  321. any(tasks);
  322. }
  323. , 'pull' : (label) => {
  324. var env = Object.assign({}, process.env); // Shallow clone it.
  325. // console.dir(env)
  326. console.log('Running exlr pull : ' + path.dirname(__dirname))
  327. // nodeShellExec('cmd', ['/c', 'setup\\utility\\chess.bat', 'pull'], {
  328. // // nodeShellExec('cmd', ['/c', '..\\setup\\utility\\chess.bat', 'pull'], {
  329. // stdio: ['pipe', process.stdout, process.stderr],
  330. // inherit : true,
  331. // shell: true,
  332. // cwd : path.dirname(__dirname),
  333. // env: env
  334. // })
  335. var performPull = repo => {
  336. if(existsSync(repo)) {
  337. console.log('pulling ' + repo)
  338. return nodeShellExec('git', ['pull'], {
  339. inherit : true, shell: true,
  340. cwd : repo
  341. // , env: process.env
  342. , runas : processedArgs.runas
  343. , title : `git pull ${repo}`
  344. }).catch((e)=>{ console.error(e) })
  345. }
  346. else {
  347. console.log('cloning ' + repo)
  348. return nodeShellExec('git', ['clone', '//172.16.0.27/repos/' + repo + '.git'],
  349. {
  350. inherit : true, shell: true,
  351. env: process.env
  352. , runas : processedArgs.runas
  353. , title : `git clone ${'//172.16.0.27/repos/' + repo + '.git'}`
  354. }).catch((e)=>{ console.error(e) })
  355. }
  356. }
  357. if(!processedArgs.runas) gitRepos.forEach(performPull)
  358. return isRunningElevated().then(
  359. (isElevated) => {
  360. if(isElevated) {
  361. any(elevatedRunasRepos.map((repo)=>performPull(repo))).then(()=>{
  362. fs.writeFileSync('run.done', 'success')
  363. }).catch(()=>{
  364. fs.writeFileSync('run.done', 'error')
  365. })
  366. }
  367. else throw false;
  368. }
  369. ).catch(
  370. () => {
  371. op['runas']()
  372. }
  373. )
  374. }
  375. , 'npmi' : ()=>{
  376. var tasks = [];
  377. gitRepos.forEach(repo => {
  378. console.log('npm i for ' + repo)
  379. // nodeShellExec('pwd', [], {
  380. // // inherit : true, shell: true
  381. // cwd : repo
  382. // // , env: process.env
  383. // , title : `pwd for ${repo}`
  384. // }).catch((e)=>{ console.error(e) })
  385. nodeShellExec('rm', ['package-lock.json'], {
  386. inherit : true, shell: true
  387. , cwd : repo
  388. , env: process.env
  389. , title : `rm 'package-lock.json' for ${repo}`
  390. }).catch((e)=>{ console.error(e) })
  391. tasks.push(()=>{
  392. var p = nodeShellExec('npm', ['i'], {
  393. inherit : true, shell: true
  394. , cwd : repo
  395. , env: process.env
  396. , title : `npm i for ${repo}`
  397. }).catch((e)=>{ console.error(e) })
  398. return p;
  399. })
  400. })
  401. any(tasks);
  402. }
  403. , 'start' : (label)=>{
  404. console.log('Starting Elixir Server.');
  405. var env = Object.assign({}, process.env); // Shallow clone it.
  406. // console.dir(env)
  407. env.NODE_ENV = label || 'development';
  408. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  409. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  410. // cmd = 'node'
  411. var childPromise = nodeShellExec(cmd, ['--inspect=9228', 'elixir/server.js'], {
  412. // inherit : true,
  413. shell: true,
  414. detached: true,
  415. stdio: 'ignore',
  416. cwd : 'elixir-server'
  417. , env: env
  418. })
  419. var child = childPromise.process;
  420. if (typeof child.pid !== 'undefined') {
  421. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  422. encoding: 'utf8'
  423. })
  424. }
  425. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  426. // inherit : true,
  427. // shell: true, detached: true,
  428. // cwd : 'qms/server',
  429. // env: env,
  430. // shell : true
  431. // })
  432. // nodeShellExec('ember', ['s'], {
  433. // // inherit : true,
  434. // shell: true, detached: true,
  435. // cwd : 'client/',
  436. // env: env
  437. // })
  438. var childPromise = nodeShellExec('ember', ['s'], {
  439. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  440. // PB : TODO -- ember debugging.
  441. // inherit : true,
  442. shell: true,
  443. detached: true,
  444. stdio: 'ignore',
  445. cwd : 'client'
  446. , env: env
  447. })
  448. // .catch(e=>console.error(e))
  449. child = childPromise.process;
  450. if (typeof child.pid !== 'undefined') {
  451. fs.writeFileSync('.client.server.pid', child.pid, {
  452. encoding: 'utf8'
  453. })
  454. }
  455. }
  456. , 'stop' : (label)=>{
  457. const kill = require('tree-kill');
  458. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  459. encoding: 'utf8'
  460. })
  461. fs.unlinkSync('.elixir-server.elixir.server.pid')
  462. console.log(serverPid)
  463. kill(serverPid)
  464. serverPid = fs.readFileSync('.client.server.pid', {
  465. encoding: 'utf8'
  466. })
  467. fs.unlinkSync('.client.server.pid')
  468. console.log(serverPid)
  469. kill(serverPid)
  470. }
  471. , 'use' : ()=>{
  472. var runconfig = { NODE_ENV : process.env.NODE_ENV }
  473. try {
  474. runconfig = Object.assign(runconfig, require('../run.js'))
  475. } catch(e) { }
  476. if(runconfig.NODE_ENV === process.env.NODE_ENV && processedArgs._[1] && runconfig.use === processedArgs._[1]) return;
  477. var tasks = [
  478. ()=>{
  479. var p = nodeShellExec('rm', ['config']
  480. , { inherit : true, shell: true, env: process.env }
  481. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  482. return p;
  483. },
  484. ()=>{
  485. var p = nodeShellExec('rm', ['data'], { inherit : true, shell: true, env: process.env }
  486. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  487. return p;
  488. }
  489. ];
  490. any(tasks)
  491. if(!processedArgs.runas) return op['runas']()
  492. process.env.NODE_ENV = process.env.NODE_ENV || 'development';
  493. if(processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  494. if(!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  495. fs.writeFileSync('../run.js', 'module.exports = ' + JSON.stringify(runconfig))
  496. tasks = [
  497. ()=>{
  498. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-' + process.env.NODE_ENV + '-config'], {
  499. inherit : true, shell: true
  500. , env: process.env
  501. }).catch((e)=>{ console.error(e) })
  502. return p;
  503. }
  504. ];
  505. if(processedArgs._[1]) {
  506. tasks.concat(
  507. [
  508. ()=>{
  509. var p = nodeShellExec('mklink', ['/D', 'data', runconfig.use + '-data'], {
  510. inherit : true, shell: true
  511. , env: process.env
  512. }).catch((e)=>{ console.error(e) })
  513. return p;
  514. }
  515. ]
  516. )
  517. }
  518. any(tasks)
  519. // Antibiotic stewardship program.
  520. // 1st use is fine.
  521. // Max vials dispense
  522. // 2nd use Pharmacy needs justification Form.
  523. // Approval after a certain period of time.
  524. }
  525. , 'g' : ()=>{
  526. if(processedArgs.h) {
  527. console.log('elxr g [modelname] => generate a model named [modelname]');
  528. console.log('elxr g => regenerate all known models');
  529. return
  530. }
  531. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  532. // console.log('Starting directory: ' + process.cwd());
  533. // try {
  534. // child = child.on('close', () => { process.chdir(label) } );
  535. // console.log('New directory: ' + process.cwd());
  536. // }
  537. // catch (err) {
  538. // console.log('chdir: ' + err);
  539. // }
  540. // child.on('close', function(){
  541. // var options = {
  542. // shell : true
  543. // , inherit : true
  544. // // , cwd : '' + process.cwd
  545. // // , env : process.env
  546. // };
  547. // nodeShellExec('git', ['init'], { inherit : true});
  548. if(0){
  549. // PB : TODO -- Special google chrome profile for tests etc.
  550. nodeShellExec('pwd', { inherit : true});
  551. //$ "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 1" http://localhost:4200/tests/index.html?grep=loopback
  552. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  553. "--profile-directory=Profile 1"
  554. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  555. }
  556. // nodeShellExec('npm', ['init', '-y'], options);
  557. // nodeShellExec('npm', ['init', '-y'], options);
  558. // })
  559. var g = {
  560. 'client' : ()=>{
  561. console.info('Creating new ember client named : ' + processedArgs._[2] ) ;
  562. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  563. stdio: ['pipe', process.stdout, process.stderr],
  564. inherit : true,
  565. shell: true,
  566. cwd : path.dirname(__dirname),
  567. env: env
  568. })
  569. }
  570. }
  571. g[processedArgs._[1]]();
  572. }
  573. }
  574. return op[label] ? op[label]() : null;
  575. }
  576. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  577. // mysql -u root -p db_name < drop_all_tables.sql
  578. var mysql = '../xampp/mysql/bin/mysql'
  579. var mysqldump = '../xampp/mysql/bin/mysqldump'
  580. // --runas
  581. if(processedArgs.runas) {
  582. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  583. __runcmd('runas')
  584. }
  585. else __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  586. function nodeShellExec() {
  587. var args = Array.from(arguments);
  588. var opts = args[2] = args[2] || {}
  589. opts.title ? null : opts.title = `${args[0]} ${args[1] }`
  590. const child = spawn(...arguments);
  591. var p = new Promise(function(resolve, reject){
  592. if(!opts.detached) {
  593. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  594. var succes = true;
  595. // use child.stdout.setEncoding('utf8'); if you want text chunks
  596. child.stdout.setEncoding('utf8');
  597. child.stderr.setEncoding('utf8');
  598. child.stdout.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  599. child.on('error', (chunk) => { succes = false; messages.push(chunk); /*console.error(chunk)*/ });
  600. child.stderr.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  601. // child.stderr.pipe(process.stderr);
  602. child.on('close', (code) => {
  603. if(code !== 0) succes = false;
  604. if(opts.runas){
  605. fs.writeFileSync('run.log', ', ' + JSON.stringify({ result: ` ${opts.title} exited with code ${code}`, messages : messages }), {'flag':'a+'} )
  606. }
  607. else {
  608. succes ? console.log(['success : ' + ` ${opts.title} exited with code ${code}`]) : console.error([`error : ${opts.title} exited with code ${code}`])
  609. // console.log( messages.join('') )
  610. process.stdout.write( messages.join('') )
  611. }
  612. if(code !== 0) return reject(code)
  613. resolve(true)
  614. });
  615. }
  616. else {
  617. child.unref()
  618. resolve(true);
  619. }
  620. });
  621. p.process = child;
  622. return p;
  623. }