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

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