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.

index.js 41KB

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