Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

index.js 46KB

před 3 roky
před 6 roky
před 4 roky
před 4 roky
před 3 roky
před 5 roky
před 6 roky
před 3 roky
před 4 roky
před 6 roky
před 5 roky
před 6 roky
před 4 roky
před 3 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 6 roky
před 5 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 3 roky
před 3 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 5 roky
před 4 roky
před 5 roky
před 5 roky
před 5 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 4 roky
před 5 roky
před 4 roky
před 5 roky
před 3 roky
před 5 roky
před 4 roky
před 5 roky
před 4 roky
před 3 roky
před 4 roky
před 3 roky
před 5 roky
před 6 roky
před 5 roky
před 6 roky
před 5 roky
před 6 roky
před 6 roky
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235
  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 = true;
  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. gitRepos.forEach(repo => {
  691. console.log('npm i for ' + repo)
  692. // nodeShellExec('pwd', [], {
  693. // // inherit : true, shell: true
  694. // cwd : repo
  695. // // , env: process.env
  696. // , title : `pwd for ${repo}`
  697. // }).catch((e)=>{ console.error(e) })
  698. nodeShellExec('rm', ['package-lock.json'], {
  699. inherit : true, shell: true
  700. , cwd : repo
  701. , env: process.env
  702. , title : `rm 'package-lock.json' for ${repo}`
  703. }).catch((e)=>{ console.error(e) })
  704. tasks.push(()=>{
  705. var p = nodeShellExec('npm', ['i'], {
  706. inherit : true, shell: true
  707. , cwd : repo
  708. , env: process.env
  709. , title : `npm i for ${repo}`
  710. }).catch((e)=>{ console.error(e) })
  711. return p;
  712. })
  713. })
  714. any(tasks);
  715. }
  716. , 'start' : (label)=>{
  717. console.log('Starting Elixir Server.');
  718. var env = Object.assign({}, process.env); // Shallow clone it.
  719. // console.dir(env)
  720. env.NODE_ENV = process.env.NODE_ENV || 'development';
  721. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  722. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  723. // cmd = 'node'
  724. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
  725. var childPromise = nodeShellExec(...cmd, {
  726. // inherit : true,
  727. shell: true,
  728. detached: true,
  729. stdio: 'ignore',
  730. cwd : 'elixir-server'
  731. , env: env
  732. })
  733. var child = childPromise.process;
  734. if (typeof child.pid !== 'undefined') {
  735. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  736. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  737. encoding: 'utf8'
  738. })
  739. }
  740. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  741. // inherit : true,
  742. // shell: true, detached: true,
  743. // cwd : 'qms/server',
  744. // env: env,
  745. // shell : true
  746. // })
  747. // nodeShellExec('ember', ['s'], {
  748. // // inherit : true,
  749. // shell: true, detached: true,
  750. // cwd : 'client/',
  751. // env: env
  752. // })
  753. console.log('Starting Elixir Client Host.');
  754. var cmd = ['ember', ['s']]
  755. var childPromise = nodeShellExec(...cmd, {
  756. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  757. // PB : TODO -- ember debugging.
  758. // inherit : true,
  759. shell: true,
  760. detached: true,
  761. stdio: 'ignore',
  762. cwd : 'client'
  763. , env: env
  764. })
  765. // .catch(e=>console.error(e))
  766. child = childPromise.process;
  767. if (typeof child.pid !== 'undefined') {
  768. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  769. fs.writeFileSync('.client.server.pid', child.pid, {
  770. encoding: 'utf8'
  771. })
  772. }
  773. }
  774. , 'stop' : (label)=>{
  775. const kill = require('tree-kill');
  776. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  777. encoding: 'utf8'
  778. })
  779. fs.unlinkSync('.elixir-server.elixir.server.pid')
  780. console.log(serverPid)
  781. kill(serverPid)
  782. serverPid = fs.readFileSync('.client.server.pid', {
  783. encoding: 'utf8'
  784. })
  785. fs.unlinkSync('.client.server.pid')
  786. console.log(serverPid)
  787. kill(serverPid)
  788. }
  789. , 'use' : ()=>{
  790. // use a certain named instance.
  791. // Eg :
  792. // 1) elxr use elixir
  793. // 2) elxr use cihsr
  794. // If environment is not specified defaults to development.
  795. // 1) NODE=test elxr use elixir
  796. /*// Steps
  797. 1) Delete Config and Data symlinks
  798. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  799. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  800. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  801. 5) Iterates all repos and merge from source configured in mergeSource. 'git', ['merge', mergeSource],
  802. */
  803. var runconfig = { NODE_ENV : process.env.NODE_ENV }
  804. try { runconfig = Object.assign(runconfig, require('../run.js')) } catch(e) { }
  805. if((!processedArgs.runas || processedArgs.runas !== 'self') &&
  806. runconfig.NODE_ENV && runconfig.NODE_ENV === (process.env.NODE_ENV || runconfig.NODE_ENV) &&
  807. processedArgs._[1] && runconfig.use === processedArgs._[1]) {
  808. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  809. if(processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  810. return
  811. }
  812. var tasks = [
  813. ()=>{
  814. if(existsSync('config')) {
  815. var p = nodeShellExec('rmdir', ['config'], {inherit : true, shell: true, env: process.env }
  816. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  817. return p;
  818. }
  819. else return Promise.resolve(true);
  820. },
  821. ()=>{
  822. if(existsSync('data')) {
  823. var p = nodeShellExec('rmdir', ['data'], { inherit : true, shell: true, env: process.env }
  824. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  825. return p;
  826. }
  827. else return Promise.resolve(true);
  828. },
  829. ];
  830. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  831. if(processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  832. if(!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  833. // console.log(process.env.cwd)
  834. fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
  835. var checkoutMap = {
  836. 'development' : 'master',
  837. }
  838. // cant use git checkout -b it fails with branch already exists.
  839. var performCheckout = (repo, branch)=>{
  840. if(!branch) return Promise.resolve({ 'skipped' : true })
  841. if(excludeCheckouts[repo]) return Promise.resolve({ 'skipped' : true })
  842. return nodeShellExec('git', ['checkout', branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  843. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  844. // inherit : true, shell: true,
  845. cwd : repo
  846. // , stdio : ignore // Use when we want to silcence output completely.
  847. , runas : processedArgs.runas
  848. , title : `git checkout ${branch ||checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${repo}`
  849. }).catch((e)=>{ console.error(e); return { error : true, message : repo} })
  850. }
  851. if(runconfig.NODE_ENV === 'development') performCheckout = ()=>{ return Promise.resolve(true) }
  852. var performPullAll = (repo)=>{
  853. if(excludeCheckouts[repo]) return Promise.resolve({ 'skipped' : true })
  854. return nodeShellExec('git', ['pull', '--all'], {
  855. // inherit : true, shell: true,
  856. cwd : repo
  857. , runas : processedArgs.runas
  858. , title : `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${repo}`
  859. }).catch((e)=>{ console.error(e); return { error : true, message : repo} })
  860. }
  861. var mergeSources = {
  862. 'development' : null,
  863. 'test' : 'master',
  864. 'production' : 'master'
  865. }
  866. var excludeCheckouts = Object.assign(exludeMergeRepos)
  867. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  868. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  869. var mergeSource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  870. var performMerge = (repo)=>{
  871. if(exludeMergeRepos[repo]) return Promise.resolve({ 'skipped' : true })
  872. return nodeShellExec('git', ['merge', mergeSource], {
  873. inherit : true, shell: true,
  874. cwd : repo
  875. , runas : processedArgs.runas
  876. }).catch((e)=>{ console.error(e) })
  877. }
  878. if(runconfig.NODE_ENV === 'development') performMerge = ()=>{ return Promise.resolve(true) }
  879. any(tasks).then(()=>{
  880. if(!processedArgs.runas) return op['runas']()
  881. tasks = [
  882. ()=>{
  883. // Use junctions to avoid npm package issues
  884. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV ], {
  885. inherit : true, shell: true
  886. , env: process.env
  887. }).catch((e)=>{ console.error(e) })
  888. return p;
  889. }
  890. ];
  891. if(processedArgs._[1]) {
  892. tasks = tasks.concat(
  893. [
  894. ()=>{
  895. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  896. inherit : true, shell: true
  897. , env: process.env
  898. }).catch((e)=>{ console.error(e) })
  899. return p;
  900. }
  901. ]
  902. )
  903. }
  904. return any(tasks)
  905. //target is the env is we specify in elxr use command. Default is dev
  906. .then( //Switch to target branch
  907. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))
  908. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))]) )
  909. .then( //PULL from target branch
  910. () => any([ any(gitRepos.map((repo)=>performPullAll(repo))), any(elevatedRunasRepos.map((repo)=>performPullAll(repo)))]) )
  911. .then( //Switch to merge source branch
  912. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'] )))
  913. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'])))]) )
  914. .then( //Pull on merge source branch
  915. () => any([ any(gitRepos.map((repo)=>performPullAll(repo))), any(elevatedRunasRepos.map((repo)=>performPullAll(repo)))]) )
  916. .then( //Switch to target branch
  917. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))
  918. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))]) )
  919. .then( //Merge source branch to target branch
  920. () => any([ any(gitRepos.map((repo)=>performMerge(repo))).catch(err=>{ console.error('error in performMerge ' + err)}) ,
  921. any(elevatedRunasRepos.map((repo)=>performMerge(repo))).catch(err=>{ console.error('error in performMerge ' + err)})]) )
  922. .then( () => {
  923. // Move test config from dev.
  924. // if(process.env.NODE_ENV === 'test'){
  925. // var devcfgreponame = runconfig.use + '-config' + '-development';
  926. // var testcfgreponame = runconfig.use + '-config' + '-test';
  927. // var testcfgdir = path.dirname(__dirname) + '/' + testcfgreponame + '/'
  928. // var devcfgdir = path.dirname(__dirname) + '/' + devcfgreponame + '/' //eg (elxr/../elixir-config.development)
  929. // return any([
  930. // ()=>{
  931. // return nodeShellExec('git', ['checkout', 'test'], {
  932. // inherit : true, shell: true,
  933. // cwd : testcfgdir
  934. // // , env: process.env
  935. // , runas : processedArgs.runas
  936. // , title : `git checkout test for ${testcfgreponame}`
  937. // }).catch((e)=>{ console.error(e) })
  938. // }
  939. // , ()=> {
  940. // return nodeShellExec('git', ['checkout', 'master'], {
  941. // inherit : true, shell: true,
  942. // cwd : devcfgdir
  943. // // , env: process.env
  944. // , runas : processedArgs.runas
  945. // , title : `git checkout master for ${devcfgreponame}`
  946. // }).catch((e)=>{ console.error(e) })
  947. // }
  948. // , ()=> {
  949. // globSync( '**/*.test.js', {cwd : devcfgdir}).map((filename) => {
  950. // console.log('File found : ' + devcfgdir + filename)
  951. // fs.copyFileSync(devcfgdir + filename, testcfgdir+ filename);
  952. // })
  953. // return nodeShellExec('git', ['checkout', 'test'], {
  954. // inherit : true, shell: true,
  955. // cwd : devcfgdir
  956. // // , env: process.env
  957. // , runas : processedArgs.runas
  958. // , title : `git checkout test for ${devcfgreponame}`
  959. // }).catch((e)=>{ console.error(e) })
  960. // }
  961. // ])
  962. // }
  963. // else {
  964. return Promise.resolve(true)
  965. // }
  966. })
  967. .then(()=>{
  968. fs.writeFileSync('run.done', 'success')
  969. }).catch(()=>{
  970. fs.writeFileSync('run.done', 'error')
  971. })
  972. }).catch(()=>{
  973. fs.writeFileSync('run.done', 'error')
  974. })
  975. // Antibiotic stewardship program.
  976. // 1st use is fine.
  977. // Max vials dispense
  978. // 2nd use Pharmacy needs justification Form.
  979. // Approval after a certain period of time.
  980. }
  981. , 'g' : ()=>{
  982. if(processedArgs.h) {
  983. console.log('elxr g [modelname] => generate a model named [modelname]');
  984. console.log('elxr g => regenerate all known models');
  985. return
  986. }
  987. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  988. // console.log('Starting directory: ' + process.cwd());
  989. // try {
  990. // child = child.on('close', () => { process.chdir(label) } );
  991. // console.log('New directory: ' + process.cwd());
  992. // }
  993. // catch (err) {
  994. // console.log('chdir: ' + err);
  995. // }
  996. // child.on('close', function(){
  997. // var options = {
  998. // shell : true
  999. // , inherit : true
  1000. // // , cwd : '' + process.cwd
  1001. // // , env : process.env
  1002. // };
  1003. // nodeShellExec('git', ['init'], { inherit : true});
  1004. if(0){
  1005. // PB : TODO -- Special google chrome profile for tests etc.
  1006. nodeShellExec('pwd', { inherit : true});
  1007. // /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"
  1008. // "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
  1009. // "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
  1010. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1011. "--profile-directory=Profile 1"
  1012. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1013. }
  1014. // nodeShellExec('npm', ['init', '-y'], options);
  1015. // nodeShellExec('npm', ['init', '-y'], options);
  1016. // })
  1017. var g = {
  1018. 'client' : ()=>{
  1019. console.info('Creating new ember client named : ' + processedArgs._[2] ) ;
  1020. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1021. stdio: ['pipe', process.stdout, process.stderr],
  1022. inherit : true,
  1023. shell: true,
  1024. cwd : path.dirname(__dirname),
  1025. env: env
  1026. })
  1027. },
  1028. 'modelr' : ()=>{
  1029. var tasks = [
  1030. ()=>{
  1031. var p = nodeShellExec('"ember"', [
  1032. 'g'
  1033. , 'modelr'
  1034. , processedArgs._[2]], {
  1035. inherit : true, shell: true, env: process.env
  1036. }).then(()=>{
  1037. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  1038. return true;
  1039. }).catch((e)=>{ console.error(e) })
  1040. return p;
  1041. },
  1042. ()=>{
  1043. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1044. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  1045. chromeprefs = JSON.parse(chromeprefs)
  1046. var previous = chromeprefs.download.default_directory;
  1047. var parentDir = path.dirname(__dirname);
  1048. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1049. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1050. // PB : TODO -- detect where chrome is installed.
  1051. // PB : TODO -- set the download dir to the place where files are needed.
  1052. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1053. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1054. , '--profile-directory="chess"'
  1055. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1056. inherit : true, shell: true
  1057. , env: process.env
  1058. }).then(()=>{
  1059. chromeprefs.download.default_directory = previous;
  1060. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1061. return true;
  1062. }).catch((e)=>{ console.error(e) })
  1063. return p;
  1064. }
  1065. ,
  1066. ()=>{
  1067. console.log('Browser process should have closed here....')
  1068. return true;
  1069. }
  1070. ]
  1071. any(tasks)
  1072. }
  1073. }
  1074. g[processedArgs._[1]]();
  1075. }
  1076. }
  1077. return op[label] ? op[label]() : null;
  1078. }
  1079. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  1080. // mysql -u root -p db_name < drop_all_tables.sql
  1081. var mysql = '../xampp/mysql/bin/mysql'
  1082. var mysqldump = '../xampp/mysql/bin/mysqldump'
  1083. // --runas
  1084. if(processedArgs.runas) {
  1085. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  1086. __runcmd('runas')
  1087. }
  1088. else __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  1089. function nodeShellExec() {
  1090. var args = Array.from(arguments);
  1091. var opts = args[2] = args[2] || {}
  1092. opts.title ? null : opts.title = `${args[0]} ${args[1] }`
  1093. const child = spawn(...arguments);
  1094. var p = new Promise(function(resolve, reject){
  1095. if(!opts.detached) {
  1096. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  1097. var success = true;
  1098. if(opts.stdio !== 'ignore') {
  1099. child.stdout.setEncoding('utf8');
  1100. child.stderr.setEncoding('utf8');
  1101. child.stdout.on('data', (chunk) => { chunk.trim() === '' ? null : messages.push(chunk); /* console.log('d: ' + chunk) */ });
  1102. child.on('error', (chunk) => { success = false; messages.push(chunk); /* console.error('e: ' + chunk) */ } );
  1103. child.stderr.on('data', (chunk) => { messages.push(chunk);
  1104. // console.error('stderr e: ' + chunk)
  1105. });
  1106. }
  1107. child.on('close', (code) => {
  1108. if(+code !== 0) success = false;
  1109. if(opts.stdio !== 'ignore') {
  1110. if(opts.runas){
  1111. var logEntry = { result: `${opts.title} exited with code ${code}`, messages : messages }
  1112. success ? logEntry.success = true : null;
  1113. fs.writeFileSync('run.log', ', ' + JSON.stringify(logEntry), {'flag':'a+'} )
  1114. }
  1115. else {
  1116. success ? console.log(['success : ' + ` ${opts.title} exited with code ${code}`]) : console.error([`error : ${opts.title} exited with code ${code}`])
  1117. // console.log( messages.join('') )
  1118. process.stdout.write( messages.join('') )
  1119. }
  1120. }
  1121. if(code !== 0) return reject(code)
  1122. resolve(messages)
  1123. });
  1124. }
  1125. else {
  1126. child.unref()
  1127. resolve(true);
  1128. }
  1129. });
  1130. p.process = child;
  1131. return p;
  1132. }