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 40KB

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