Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

index.js 45KB

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