555
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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