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

index.js 47KB

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