555
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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