Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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