您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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