555
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

index.js 47KB

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