Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

index.js 40KB

6 år sedan
4 år sedan
4 år sedan
5 år sedan
6 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
6 år sedan
5 år sedan
6 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
6 år sedan
5 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
5 år sedan
4 år sedan
5 år sedan
5 år sedan
5 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
4 år sedan
5 år sedan
5 år sedan
5 år sedan
5 år sedan
6 år sedan
5 år sedan
6 år sedan
5 år sedan
6 år sedan
6 år sedan
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  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. remotename = remotename || processedArgs._[1]
  388. url = url || processedArgs._[2]
  389. branch = branch || processedArgs._[3]
  390. var serial_perform_git_add = (repo)=>{
  391. var options = { cwd : repo }
  392. // console.log(repo)
  393. return [
  394. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd : repo }]
  395. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd : repo }]
  396. , ['git', ['pull', remotename, branch], { cwd : repo }]
  397. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd : repo }]
  398. ]
  399. }
  400. var x = (args)=>{
  401. return ()=>{
  402. // console.log(args)
  403. return nodeShellExec.apply(null, args)
  404. }
  405. // return Promise.resolve(true)
  406. }
  407. var perform_git_add = (dir)=>{
  408. op['is-git-repo'](dir).then((code)=>{
  409. // console.log(code)
  410. if(code) {
  411. nodeShellExec('git',['remote', 'get-url', remotename], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  412. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  413. })
  414. .catch((e)=>{
  415. any( serial_perform_git_add(dir.name).map(x) )
  416. })
  417. }
  418. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  419. }).catch((e)=>{
  420. // console.log('Failed : ' + dir.name)
  421. })
  422. }
  423. const { readdir } = require("fs").promises
  424. const dirs = async (perform, path) => {
  425. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  426. if (dir.isDirectory()) perform(dir)
  427. }
  428. }
  429. dirs(perform_git_add)
  430. }
  431. , 'remove' : (remotename) => {
  432. remotename = remotename || processedArgs._[1]
  433. var serial_perform_git_remove = (repo)=>{
  434. var options = { cwd : repo }
  435. // console.log(repo)
  436. return [
  437. ['git', ['remote', 'remove', remotename], { cwd : repo }]
  438. ]
  439. }
  440. var x = (args)=>{
  441. return ()=>{
  442. // console.log(args)
  443. return nodeShellExec.apply(null, args)
  444. }
  445. // return Promise.resolve(true)
  446. }
  447. var perform_git_remove = (dir)=>{
  448. op['is-git-repo'](dir).then((code)=>{
  449. // console.log(code)
  450. if(code) {
  451. nodeShellExec('git',['remote', 'get-url', remotename], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  452. any( serial_perform_git_remove(dir.name).map(x) )
  453. })
  454. .catch((e)=>{
  455. console.log('skipped : ' + dir.name + ', reason : No remote named origin')
  456. })
  457. }
  458. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  459. }).catch((e)=>{
  460. // console.log('Failed : ' + dir.name)
  461. })
  462. }
  463. const { readdir } = require("fs").promises
  464. const dirs = async (perform, path) => {
  465. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  466. if (dir.isDirectory()) perform(dir)
  467. }
  468. }
  469. dirs(perform_git_remove)
  470. }
  471. , 'init-gitea' : (user) => {
  472. user = user || processedArgs._[1]
  473. if(!user) throw 'User name required'
  474. var serial_perform_init_gitea = (repo)=>{
  475. var options = { cwd : repo }
  476. // console.log(repo)
  477. return [
  478. ['git', ['remote', 'add', 'chess', 'http://git.bbh/chess/elxr.git'], { cwd : repo }]
  479. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd : repo }]
  480. , ['git', ['remote', 'set-url', 'origin', `http://git.bbh/${user}/${repo}.git`], { cwd : repo }]
  481. ]}
  482. var x = (args)=>{
  483. return ()=>{
  484. // console.log(args)
  485. return nodeShellExec.apply(null, args)
  486. }
  487. // return Promise.resolve(true)
  488. }
  489. var perform_init_gitea = (dir)=>{
  490. op['is-git-repo'](dir).then((code)=>{
  491. // console.log(code)
  492. if(code) {
  493. nodeShellExec('git',['remote', 'get-url', 'chess'], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  494. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  495. })
  496. .catch((e)=>{
  497. any( serial_perform_init_gitea(dir.name).map(x) )
  498. })
  499. }
  500. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  501. }).catch((e)=>{
  502. // console.log('Failed : ' + dir.name)
  503. })
  504. }
  505. const { readdir } = require("fs").promises
  506. const dirs = async (perform, path) => {
  507. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  508. if (dir.isDirectory()) perform(dir)
  509. }
  510. }
  511. dirs(perform_init_gitea)
  512. }
  513. , 'pull' : (label) => {
  514. // Usage :
  515. // elxr pull -- Defaults to run config
  516. var env = Object.assign({}, process.env); // Shallow clone it.
  517. // console.dir(env)
  518. console.log('Running exlr pull : ' + path.dirname(__dirname))
  519. // nodeShellExec('cmd', ['/c', 'setup\\utility\\chess.bat', 'pull'], {
  520. // // nodeShellExec('cmd', ['/c', '..\\setup\\utility\\chess.bat', 'pull'], {
  521. // stdio: ['pipe', process.stdout, process.stderr],
  522. // inherit : true,
  523. // shell: true,
  524. // cwd : path.dirname(__dirname),
  525. // env: env
  526. // })
  527. var useGitPull = processedArgs.useGitPull || false;
  528. var getPullCmd = (repo)=>{
  529. // console.log(useGitPull)
  530. var pullCmd = ["C:\\Program Files\\Git\\bin\\sh.exe"
  531. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  532. , { cwd : repo, title : 'pull all origins for ' + repo }]
  533. // var pullCmd = ['pullall', [], { cwd : repo }]
  534. if(useGitPull) pullCmd = ['git', ['pull'], {
  535. inherit : true, shell: true,
  536. cwd : repo
  537. // , env: process.env
  538. , runas : processedArgs.runas
  539. , title : `git pull ${repo}`
  540. }]
  541. return pullCmd
  542. }
  543. var performPull = (repo) => {
  544. if(existsSync(repo)) {
  545. console.log('pulling ' + repo)
  546. return nodeShellExec.apply(null, getPullCmd(repo)).catch((e)=>{ console.error(e) })
  547. }
  548. else {
  549. console.log('cloning ' + repo)
  550. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', defaultRepoServer + '/' + repo + '.git'],
  551. {
  552. inherit : true, shell: true,
  553. env: process.env
  554. , runas : processedArgs.runas
  555. }).catch((e)=>{ console.error(e) }).then(()=>{
  556. return nodeShellExec('git', ['config', '--replace-all' , 'core.symlinks', true],
  557. {
  558. inherit : true, shell: true,
  559. env: process.env
  560. , cwd : repo
  561. , runas : processedArgs.runas
  562. , title : `git core.symlinks --replace-all true for ${defaultRepoServer + '/' + repo + '.git'}`
  563. })
  564. })
  565. }
  566. }
  567. if(!processedArgs.runas) gitRepos.forEach(performPull)
  568. return isRunningElevated().then(
  569. (isElevated) => {
  570. if(isElevated) {
  571. any(elevatedRunasRepos.map((repo)=>performPull(repo))).then(()=>{
  572. fs.writeFileSync('run.done', 'success')
  573. }).catch(()=>{
  574. fs.writeFileSync('run.done', 'error')
  575. })
  576. }
  577. else throw false;
  578. }
  579. ).catch(
  580. () => {
  581. op['runas']()
  582. }
  583. )
  584. }
  585. , 'isInstalled' : ()=>{
  586. return nodeShellExec('where', [processedArgs._[1]], { inherit : true} ).then(()=>{
  587. console.log(processedArgs._[1] + ' exists.')
  588. return true;
  589. });
  590. }
  591. , 'npmi' : ()=>{
  592. var tasks = [];
  593. gitRepos.forEach(repo => {
  594. console.log('npm i for ' + repo)
  595. // nodeShellExec('pwd', [], {
  596. // // inherit : true, shell: true
  597. // cwd : repo
  598. // // , env: process.env
  599. // , title : `pwd for ${repo}`
  600. // }).catch((e)=>{ console.error(e) })
  601. nodeShellExec('rm', ['package-lock.json'], {
  602. inherit : true, shell: true
  603. , cwd : repo
  604. , env: process.env
  605. , title : `rm 'package-lock.json' for ${repo}`
  606. }).catch((e)=>{ console.error(e) })
  607. tasks.push(()=>{
  608. var p = nodeShellExec('npm', ['i'], {
  609. inherit : true, shell: true
  610. , cwd : repo
  611. , env: process.env
  612. , title : `npm i for ${repo}`
  613. }).catch((e)=>{ console.error(e) })
  614. return p;
  615. })
  616. })
  617. any(tasks);
  618. }
  619. , 'start' : (label)=>{
  620. console.log('Starting Elixir Server.');
  621. var env = Object.assign({}, process.env); // Shallow clone it.
  622. // console.dir(env)
  623. env.NODE_ENV = process.env.NODE_ENV || 'development';
  624. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  625. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  626. // cmd = 'node'
  627. var childPromise = nodeShellExec(cmd, ['--inspect=9228', 'elixir/server.js'], {
  628. // inherit : true,
  629. shell: true,
  630. detached: true,
  631. stdio: 'ignore',
  632. cwd : 'elixir-server'
  633. , env: env
  634. })
  635. var child = childPromise.process;
  636. if (typeof child.pid !== 'undefined') {
  637. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  638. encoding: 'utf8'
  639. })
  640. }
  641. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  642. // inherit : true,
  643. // shell: true, detached: true,
  644. // cwd : 'qms/server',
  645. // env: env,
  646. // shell : true
  647. // })
  648. // nodeShellExec('ember', ['s'], {
  649. // // inherit : true,
  650. // shell: true, detached: true,
  651. // cwd : 'client/',
  652. // env: env
  653. // })
  654. var childPromise = nodeShellExec('ember', ['s'], {
  655. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  656. // PB : TODO -- ember debugging.
  657. // inherit : true,
  658. shell: true,
  659. detached: true,
  660. stdio: 'ignore',
  661. cwd : 'client'
  662. , env: env
  663. })
  664. // .catch(e=>console.error(e))
  665. child = childPromise.process;
  666. if (typeof child.pid !== 'undefined') {
  667. fs.writeFileSync('.client.server.pid', child.pid, {
  668. encoding: 'utf8'
  669. })
  670. }
  671. }
  672. , 'stop' : (label)=>{
  673. const kill = require('tree-kill');
  674. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  675. encoding: 'utf8'
  676. })
  677. fs.unlinkSync('.elixir-server.elixir.server.pid')
  678. console.log(serverPid)
  679. kill(serverPid)
  680. serverPid = fs.readFileSync('.client.server.pid', {
  681. encoding: 'utf8'
  682. })
  683. fs.unlinkSync('.client.server.pid')
  684. console.log(serverPid)
  685. kill(serverPid)
  686. }
  687. , 'use' : ()=>{
  688. // use a certain named instance.
  689. // Eg :
  690. // 1) elxr use elixir
  691. // 2) elxr use cihsr
  692. // If environment is not specified defaults to development.
  693. // 1) NODE=test elxr use elixir
  694. /*// Steps
  695. 1) Delete Config and Data symlinks
  696. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  697. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  698. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  699. 5) Iterates all repos and merge from source configured in mergeSource. 'git', ['merge', mergeSource],
  700. */
  701. var runconfig = { NODE_ENV : process.env.NODE_ENV }
  702. try { runconfig = Object.assign(runconfig, require('../run.js')) } catch(e) { }
  703. if((!processedArgs.runas || processedArgs.runas !== 'self') &&
  704. runconfig.NODE_ENV && runconfig.NODE_ENV === (process.env.NODE_ENV || runconfig.NODE_ENV) &&
  705. processedArgs._[1] && runconfig.use === processedArgs._[1]) {
  706. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  707. if(processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  708. return
  709. }
  710. var tasks = [
  711. ()=>{
  712. if(existsSync('config')) {
  713. var p = nodeShellExec('rmdir', ['config'], {inherit : true, shell: true, env: process.env }
  714. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  715. return p;
  716. }
  717. else return Promise.resolve(true);
  718. },
  719. ()=>{
  720. if(existsSync('data')) {
  721. var p = nodeShellExec('rmdir', ['data'], { inherit : true, shell: true, env: process.env }
  722. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  723. return p;
  724. }
  725. else return Promise.resolve(true);
  726. },
  727. ];
  728. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  729. if(processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  730. if(!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  731. // console.log(process.env.cwd)
  732. fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
  733. var checkoutMap = {
  734. 'development' : 'master',
  735. }
  736. // cant use git checkout -b it fails with branch already exists.
  737. var performCheckout = (repo, branch)=>{
  738. if(!branch) return Promise.resolve({ 'skipped' : true })
  739. if(excludeCheckouts[repo]) return Promise.resolve({ 'skipped' : true })
  740. return nodeShellExec('git', ['checkout', branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  741. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  742. // inherit : true, shell: true,
  743. cwd : repo
  744. // , stdio : ignore // Use when we want to silcence output completely.
  745. , runas : processedArgs.runas
  746. , title : `git checkout ${branch ||checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${repo}`
  747. }).catch((e)=>{ console.error(e); return { error : true, message : repo} })
  748. }
  749. if(runconfig.NODE_ENV === 'development') performCheckout = ()=>{ return Promise.resolve(true) }
  750. var performPullAll = (repo)=>{
  751. if(excludeCheckouts[repo]) return Promise.resolve({ 'skipped' : true })
  752. return nodeShellExec('git', ['pull', '--all'], {
  753. // inherit : true, shell: true,
  754. cwd : repo
  755. , runas : processedArgs.runas
  756. , title : `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${repo}`
  757. }).catch((e)=>{ console.error(e); return { error : true, message : repo} })
  758. }
  759. var mergeSources = {
  760. 'development' : null,
  761. 'test' : 'master',
  762. 'production' : 'master'
  763. }
  764. var exludeMergeRepos = {
  765. 'elixir-config-development' : true, 'elixir-config-test': true, 'elixir-config-production' : true
  766. , 'elixir-data' : true
  767. ,'cihsr-config-development' : true, 'cihsr-config-test': true, 'cihsr-config-production' : true
  768. , 'cihsr-data' : true
  769. }
  770. var excludeCheckouts = Object.assign(exludeMergeRepos)
  771. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  772. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  773. var mergeSource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  774. var performMerge = (repo)=>{
  775. if(exludeMergeRepos[repo]) return Promise.resolve({ 'skipped' : true })
  776. return nodeShellExec('git', ['merge', mergeSource], {
  777. inherit : true, shell: true,
  778. cwd : repo
  779. , runas : processedArgs.runas
  780. }).catch((e)=>{ console.error(e) })
  781. }
  782. if(runconfig.NODE_ENV === 'development') performMerge = ()=>{ return Promise.resolve(true) }
  783. any(tasks).then(()=>{
  784. if(!processedArgs.runas) return op['runas']()
  785. tasks = [
  786. ()=>{
  787. // Use junctions to avoid npm package issues
  788. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV ], {
  789. inherit : true, shell: true
  790. , env: process.env
  791. }).catch((e)=>{ console.error(e) })
  792. return p;
  793. }
  794. ];
  795. if(processedArgs._[1]) {
  796. tasks = tasks.concat(
  797. [
  798. ()=>{
  799. var p = nodeShellExec('mklink', ['/D', 'data', runconfig.use + '-data'], {
  800. inherit : true, shell: true
  801. , env: process.env
  802. }).catch((e)=>{ console.error(e) })
  803. return p;
  804. }
  805. ]
  806. )
  807. }
  808. return any(tasks)
  809. //target is the env is we specify in elxr use command. Default is dev
  810. .then( //Switch to target branch
  811. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))
  812. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))]) )
  813. .then( //PULL from target branch
  814. () => any([ any(gitRepos.map((repo)=>performPullAll(repo))), any(elevatedRunasRepos.map((repo)=>performPullAll(repo)))]) )
  815. .then( //Switch to merge source branch
  816. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'] )))
  817. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'])))]) )
  818. .then( //Pull on merge source branch
  819. () => any([ any(gitRepos.map((repo)=>performPullAll(repo))), any(elevatedRunasRepos.map((repo)=>performPullAll(repo)))]) )
  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( //Merge source branch to target branch
  824. () => any([ any(gitRepos.map((repo)=>performMerge(repo))).catch(err=>{ console.error('error in performMerge ' + err)}) ,
  825. any(elevatedRunasRepos.map((repo)=>performMerge(repo))).catch(err=>{ console.error('error in performMerge ' + err)})]) )
  826. .then( () => {
  827. // Move test config from dev.
  828. // if(process.env.NODE_ENV === 'test'){
  829. // var devcfgreponame = runconfig.use + '-config' + '-development';
  830. // var testcfgreponame = runconfig.use + '-config' + '-test';
  831. // var testcfgdir = path.dirname(__dirname) + '/' + testcfgreponame + '/'
  832. // var devcfgdir = path.dirname(__dirname) + '/' + devcfgreponame + '/' //eg (elxr/../elixir-config.development)
  833. // return any([
  834. // ()=>{
  835. // return nodeShellExec('git', ['checkout', 'test'], {
  836. // inherit : true, shell: true,
  837. // cwd : testcfgdir
  838. // // , env: process.env
  839. // , runas : processedArgs.runas
  840. // , title : `git checkout test for ${testcfgreponame}`
  841. // }).catch((e)=>{ console.error(e) })
  842. // }
  843. // , ()=> {
  844. // return nodeShellExec('git', ['checkout', 'master'], {
  845. // inherit : true, shell: true,
  846. // cwd : devcfgdir
  847. // // , env: process.env
  848. // , runas : processedArgs.runas
  849. // , title : `git checkout master for ${devcfgreponame}`
  850. // }).catch((e)=>{ console.error(e) })
  851. // }
  852. // , ()=> {
  853. // globSync( '**/*.test.js', {cwd : devcfgdir}).map((filename) => {
  854. // console.log('File found : ' + devcfgdir + filename)
  855. // fs.copyFileSync(devcfgdir + filename, testcfgdir+ filename);
  856. // })
  857. // return nodeShellExec('git', ['checkout', 'test'], {
  858. // inherit : true, shell: true,
  859. // cwd : devcfgdir
  860. // // , env: process.env
  861. // , runas : processedArgs.runas
  862. // , title : `git checkout test for ${devcfgreponame}`
  863. // }).catch((e)=>{ console.error(e) })
  864. // }
  865. // ])
  866. // }
  867. // else {
  868. return Promise.resolve(true)
  869. // }
  870. })
  871. .then(()=>{
  872. fs.writeFileSync('run.done', 'success')
  873. }).catch(()=>{
  874. fs.writeFileSync('run.done', 'error')
  875. })
  876. }).catch(()=>{
  877. fs.writeFileSync('run.done', 'error')
  878. })
  879. // Antibiotic stewardship program.
  880. // 1st use is fine.
  881. // Max vials dispense
  882. // 2nd use Pharmacy needs justification Form.
  883. // Approval after a certain period of time.
  884. }
  885. , 'g' : ()=>{
  886. if(processedArgs.h) {
  887. console.log('elxr g [modelname] => generate a model named [modelname]');
  888. console.log('elxr g => regenerate all known models');
  889. return
  890. }
  891. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  892. // console.log('Starting directory: ' + process.cwd());
  893. // try {
  894. // child = child.on('close', () => { process.chdir(label) } );
  895. // console.log('New directory: ' + process.cwd());
  896. // }
  897. // catch (err) {
  898. // console.log('chdir: ' + err);
  899. // }
  900. // child.on('close', function(){
  901. // var options = {
  902. // shell : true
  903. // , inherit : true
  904. // // , cwd : '' + process.cwd
  905. // // , env : process.env
  906. // };
  907. // nodeShellExec('git', ['init'], { inherit : true});
  908. if(0){
  909. // PB : TODO -- Special google chrome profile for tests etc.
  910. nodeShellExec('pwd', { inherit : true});
  911. //$ "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 1" http://localhost:4200/tests/index.html?grep=loopback
  912. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  913. "--profile-directory=Profile 1"
  914. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  915. }
  916. // nodeShellExec('npm', ['init', '-y'], options);
  917. // nodeShellExec('npm', ['init', '-y'], options);
  918. // })
  919. var g = {
  920. 'client' : ()=>{
  921. console.info('Creating new ember client named : ' + processedArgs._[2] ) ;
  922. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  923. stdio: ['pipe', process.stdout, process.stderr],
  924. inherit : true,
  925. shell: true,
  926. cwd : path.dirname(__dirname),
  927. env: env
  928. })
  929. }
  930. }
  931. g[processedArgs._[1]]();
  932. }
  933. }
  934. return op[label] ? op[label]() : null;
  935. }
  936. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  937. // mysql -u root -p db_name < drop_all_tables.sql
  938. var mysql = '../xampp/mysql/bin/mysql'
  939. var mysqldump = '../xampp/mysql/bin/mysqldump'
  940. // --runas
  941. if(processedArgs.runas) {
  942. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  943. __runcmd('runas')
  944. }
  945. else __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  946. function nodeShellExec() {
  947. var args = Array.from(arguments);
  948. var opts = args[2] = args[2] || {}
  949. opts.title ? null : opts.title = `${args[0]} ${args[1] }`
  950. const child = spawn(...arguments);
  951. var p = new Promise(function(resolve, reject){
  952. if(!opts.detached) {
  953. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  954. var success = true;
  955. if(opts.stdio !== 'ignore') {
  956. child.stdout.setEncoding('utf8');
  957. child.stderr.setEncoding('utf8');
  958. child.stdout.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  959. child.on('error', (chunk) => { success = false; messages.push(chunk); /*console.error(chunk)*/ });
  960. child.stderr.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  961. }
  962. child.on('close', (code) => {
  963. if(+code !== 0) success = false;
  964. if(opts.stdio !== 'ignore') {
  965. if(opts.runas){
  966. var logEntry = { result: `${opts.title} exited with code ${code}`, messages : messages }
  967. success ? logEntry.success = true : null;
  968. fs.writeFileSync('run.log', ', ' + JSON.stringify(logEntry), {'flag':'a+'} )
  969. }
  970. else {
  971. success ? console.log(['success : ' + ` ${opts.title} exited with code ${code}`]) : console.error([`error : ${opts.title} exited with code ${code}`])
  972. // console.log( messages.join('') )
  973. process.stdout.write( messages.join('') )
  974. }
  975. }
  976. if(code !== 0) return reject(code)
  977. resolve(true)
  978. });
  979. }
  980. else {
  981. child.unref()
  982. resolve(true);
  983. }
  984. });
  985. p.process = child;
  986. return p;
  987. }