You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 47KB

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