您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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