555
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

index.js 37KB

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