Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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