Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

index.js 37KB

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