index.js 47KB

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