555
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 40KB

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