Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

index.js 41KB

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