Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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