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

index.js 47KB

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