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 46KB

6 vuotta sitten
4 vuotta sitten
4 vuotta sitten
5 vuotta sitten
6 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
6 vuotta sitten
5 vuotta sitten
6 vuotta sitten
5 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
3 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
6 vuotta sitten
5 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
3 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
4 vuotta sitten
4 vuotta sitten
5 vuotta sitten
5 vuotta sitten
4 vuotta sitten
5 vuotta sitten
5 vuotta sitten
4 vuotta sitten
5 vuotta sitten
4 vuotta sitten
5 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
5 vuotta sitten
4 vuotta sitten
5 vuotta sitten
4 vuotta sitten
5 vuotta sitten
4 vuotta sitten
5 vuotta sitten
6 vuotta sitten
5 vuotta sitten
6 vuotta sitten
5 vuotta sitten
6 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
6 vuotta sitten
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253
  1. 
  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'
  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 = true;
  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)).catch((e)=>{
  692. errors.push({ repo , e})
  693. console.error(e) })
  694. }
  695. else {
  696. console.log('cloning ' + repo)
  697. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  698. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', defaultRepoServer + `/${defaultRepoOwner}/` + repo + '.git'],
  699. {
  700. inherit : true, shell: true,
  701. env: process.env
  702. , runas : processedArgs.runas
  703. }).catch((e)=>{
  704. errors.push({ repo , e})
  705. console.error(e)
  706. }).then(()=>{
  707. return nodeShellExec('git', ['config', '--replace-all' , 'core.symlinks', true],
  708. {
  709. inherit : true, shell: true,
  710. env: process.env
  711. , cwd : repo
  712. , runas : processedArgs.runas
  713. , title : `git core.symlinks --replace-all true for ${defaultRepoServer + `/${defaultRepoOwner}/` + repo + '.git'}`
  714. })
  715. })
  716. }
  717. }
  718. if(!processedArgs.runas) gitRepos.forEach(performPull)
  719. return isRunningElevated().then(
  720. (isElevated) => {
  721. if(isElevated) {
  722. any(elevatedRunasRepos.map((repo)=>performPull(repo))).then(()=>{
  723. fs.writeFileSync('run.done', 'success')
  724. }).catch(()=>{
  725. fs.writeFileSync('run.done', 'error')
  726. })
  727. }
  728. else throw false;
  729. }
  730. ).catch(
  731. () => {
  732. op['runas']()
  733. }
  734. )
  735. }
  736. , 'isInstalled' : ()=>{
  737. return nodeShellExec('where', [processedArgs._[1]], { inherit : true} ).then(()=>{
  738. console.log(processedArgs._[1] + ' exists.')
  739. return true;
  740. });
  741. }
  742. , 'npmi' : ()=>{
  743. var tasks = [];
  744. gitRepos.forEach(repo => {
  745. console.log('npm i for ' + repo)
  746. // nodeShellExec('pwd', [], {
  747. // // inherit : true, shell: true
  748. // cwd : repo
  749. // // , env: process.env
  750. // , title : `pwd for ${repo}`
  751. // }).catch((e)=>{ console.error(e) })
  752. nodeShellExec('rm', ['package-lock.json'], {
  753. inherit : true, shell: true
  754. , cwd : repo
  755. , env: process.env
  756. , title : `rm 'package-lock.json' for ${repo}`
  757. }).catch((e)=>{ console.error(e) })
  758. tasks.push(()=>{
  759. var p = nodeShellExec('npm', ['i'], {
  760. inherit : true, shell: true
  761. , cwd : repo
  762. , env: process.env
  763. , title : `npm i for ${repo}`
  764. }).catch((e)=>{ console.error(e) })
  765. return p;
  766. })
  767. })
  768. any(tasks);
  769. }
  770. , 'start' : (label)=>{
  771. console.log('Starting Elixir Server.');
  772. var env = Object.assign({}, process.env); // Shallow clone it.
  773. // console.dir(env)
  774. env.NODE_ENV = process.env.NODE_ENV || 'development';
  775. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  776. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  777. // cmd = 'node'
  778. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
  779. var childPromise = nodeShellExec(...cmd, {
  780. // inherit : true,
  781. shell: true,
  782. detached: true,
  783. stdio: 'ignore',
  784. cwd : 'elixir-server'
  785. , env: env
  786. })
  787. var child = childPromise.process;
  788. if (typeof child.pid !== 'undefined') {
  789. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  790. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  791. encoding: 'utf8'
  792. })
  793. }
  794. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  795. // inherit : true,
  796. // shell: true, detached: true,
  797. // cwd : 'qms/server',
  798. // env: env,
  799. // shell : true
  800. // })
  801. // nodeShellExec('ember', ['s'], {
  802. // // inherit : true,
  803. // shell: true, detached: true,
  804. // cwd : 'client/',
  805. // env: env
  806. // })
  807. console.log('Starting Elixir Client Host.');
  808. var cmd = ['ember', ['s']]
  809. var childPromise = nodeShellExec(...cmd, {
  810. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  811. // PB : TODO -- ember debugging.
  812. // inherit : true,
  813. shell: true,
  814. detached: true,
  815. stdio: 'ignore',
  816. cwd : 'client'
  817. , env: env
  818. })
  819. // .catch(e=>console.error(e))
  820. child = childPromise.process;
  821. if (typeof child.pid !== 'undefined') {
  822. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  823. fs.writeFileSync('.client.server.pid', child.pid, {
  824. encoding: 'utf8'
  825. })
  826. }
  827. }
  828. , 'stop' : (label)=>{
  829. const kill = require('tree-kill');
  830. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  831. encoding: 'utf8'
  832. })
  833. fs.unlinkSync('.elixir-server.elixir.server.pid')
  834. console.log(serverPid)
  835. kill(serverPid)
  836. serverPid = fs.readFileSync('.client.server.pid', {
  837. encoding: 'utf8'
  838. })
  839. fs.unlinkSync('.client.server.pid')
  840. console.log(serverPid)
  841. kill(serverPid)
  842. }
  843. , 'use' : ()=>{
  844. // use a certain named instance.
  845. // Eg :
  846. // 1) elxr use elixir
  847. // 2) elxr use cihsr
  848. // If environment is not specified defaults to development.
  849. // 1) NODE=test elxr use elixir
  850. /*// Steps
  851. 1) Delete Config and Data symlinks
  852. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  853. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  854. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  855. 5) Iterates all repos and merge from source configured in mergeSource. 'git', ['merge', mergeSource],
  856. */
  857. var runconfig = { NODE_ENV : process.env.NODE_ENV }
  858. try { runconfig = Object.assign(runconfig, require('../run.js')) } catch(e) { }
  859. if((!processedArgs.runas || processedArgs.runas !== 'self') &&
  860. runconfig.NODE_ENV && runconfig.NODE_ENV === (process.env.NODE_ENV || runconfig.NODE_ENV) &&
  861. processedArgs._[1] && runconfig.use === processedArgs._[1]) {
  862. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  863. if(processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  864. return
  865. }
  866. var tasks = [
  867. ()=>{
  868. if(existsSync('config')) {
  869. var p = nodeShellExec('rmdir', ['config'], {inherit : true, shell: true, env: process.env }
  870. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  871. return p;
  872. }
  873. else return Promise.resolve(true);
  874. },
  875. ()=>{
  876. if(existsSync('data')) {
  877. var p = nodeShellExec('rmdir', ['data'], { inherit : true, shell: true, env: process.env }
  878. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  879. return p;
  880. }
  881. else return Promise.resolve(true);
  882. },
  883. ];
  884. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  885. if(processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  886. if(!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  887. // console.log(process.env.cwd)
  888. fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
  889. var checkoutMap = {
  890. 'development' : 'master',
  891. }
  892. // cant use git checkout -b it fails with branch already exists.
  893. var performCheckout = (repo, branch)=>{
  894. if(!branch) return Promise.resolve({ 'skipped' : true })
  895. if(excludeCheckouts[repo]) return Promise.resolve({ 'skipped' : true })
  896. return nodeShellExec('git', ['checkout', branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  897. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  898. // inherit : true, shell: true,
  899. cwd : repo
  900. // , stdio : ignore // Use when we want to silcence output completely.
  901. , runas : processedArgs.runas
  902. , title : `git checkout ${branch ||checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${repo}`
  903. }).catch((e)=>{ console.error(e); return { error : true, message : repo} })
  904. }
  905. if(runconfig.NODE_ENV === 'development') performCheckout = ()=>{ return Promise.resolve(true) }
  906. var performPullAll = (repo)=>{
  907. if(excludeCheckouts[repo]) return Promise.resolve({ 'skipped' : true })
  908. return nodeShellExec('git', ['pull', '--all'], {
  909. // inherit : true, shell: true,
  910. cwd : repo
  911. , runas : processedArgs.runas
  912. , title : `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${repo}`
  913. }).catch((e)=>{ console.error(e); return { error : true, message : repo} })
  914. }
  915. var mergeSources = {
  916. 'development' : null,
  917. 'test' : 'master',
  918. 'production' : 'master'
  919. }
  920. var excludeCheckouts = Object.assign(exludeMergeRepos)
  921. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  922. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  923. var mergeSource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  924. var performMerge = (repo)=>{
  925. if(exludeMergeRepos[repo]) return Promise.resolve({ 'skipped' : true })
  926. return nodeShellExec('git', ['merge', mergeSource], {
  927. inherit : true, shell: true,
  928. cwd : repo
  929. , runas : processedArgs.runas
  930. }).catch((e)=>{ console.error(e) })
  931. }
  932. if(runconfig.NODE_ENV === 'development') performMerge = ()=>{ return Promise.resolve(true) }
  933. any(tasks).then(()=>{
  934. if(!processedArgs.runas) return op['runas']()
  935. tasks = [
  936. ()=>{
  937. // Use junctions to avoid npm package issues
  938. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV ], {
  939. inherit : true, shell: true
  940. , env: process.env
  941. }).catch((e)=>{ console.error(e) })
  942. return p;
  943. }
  944. ];
  945. if(processedArgs._[1]) {
  946. tasks = tasks.concat(
  947. [
  948. ()=>{
  949. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  950. inherit : true, shell: true
  951. , env: process.env
  952. }).catch((e)=>{ console.error(e) })
  953. return p;
  954. }
  955. ]
  956. )
  957. }
  958. return any(tasks)
  959. //target is the env is we specify in elxr use command. Default is dev
  960. .then( //Switch to target branch
  961. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))
  962. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))]) )
  963. .then( //PULL from target branch
  964. () => any([ any(gitRepos.map((repo)=>performPullAll(repo))), any(elevatedRunasRepos.map((repo)=>performPullAll(repo)))]) )
  965. .then( //Switch to merge source branch
  966. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'] )))
  967. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'])))]) )
  968. .then( //Pull on merge source branch
  969. () => any([ any(gitRepos.map((repo)=>performPullAll(repo))), any(elevatedRunasRepos.map((repo)=>performPullAll(repo)))]) )
  970. .then( //Switch to target branch
  971. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))
  972. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))]) )
  973. .then( //Merge source branch to target branch
  974. () => any([ any(gitRepos.map((repo)=>performMerge(repo))).catch(err=>{ console.error('error in performMerge ' + err)}) ,
  975. any(elevatedRunasRepos.map((repo)=>performMerge(repo))).catch(err=>{ console.error('error in performMerge ' + err)})]) )
  976. .then( () => {
  977. // Move test config from dev.
  978. // if(process.env.NODE_ENV === 'test'){
  979. // var devcfgreponame = runconfig.use + '-config' + '-development';
  980. // var testcfgreponame = runconfig.use + '-config' + '-test';
  981. // var testcfgdir = path.dirname(__dirname) + '/' + testcfgreponame + '/'
  982. // var devcfgdir = path.dirname(__dirname) + '/' + devcfgreponame + '/' //eg (elxr/../elixir-config.development)
  983. // return any([
  984. // ()=>{
  985. // return nodeShellExec('git', ['checkout', 'test'], {
  986. // inherit : true, shell: true,
  987. // cwd : testcfgdir
  988. // // , env: process.env
  989. // , runas : processedArgs.runas
  990. // , title : `git checkout test for ${testcfgreponame}`
  991. // }).catch((e)=>{ console.error(e) })
  992. // }
  993. // , ()=> {
  994. // return nodeShellExec('git', ['checkout', 'master'], {
  995. // inherit : true, shell: true,
  996. // cwd : devcfgdir
  997. // // , env: process.env
  998. // , runas : processedArgs.runas
  999. // , title : `git checkout master for ${devcfgreponame}`
  1000. // }).catch((e)=>{ console.error(e) })
  1001. // }
  1002. // , ()=> {
  1003. // globSync( '**/*.test.js', {cwd : devcfgdir}).map((filename) => {
  1004. // console.log('File found : ' + devcfgdir + filename)
  1005. // fs.copyFileSync(devcfgdir + filename, testcfgdir+ filename);
  1006. // })
  1007. // return nodeShellExec('git', ['checkout', 'test'], {
  1008. // inherit : true, shell: true,
  1009. // cwd : devcfgdir
  1010. // // , env: process.env
  1011. // , runas : processedArgs.runas
  1012. // , title : `git checkout test for ${devcfgreponame}`
  1013. // }).catch((e)=>{ console.error(e) })
  1014. // }
  1015. // ])
  1016. // }
  1017. // else {
  1018. return Promise.resolve(true)
  1019. // }
  1020. })
  1021. .then(()=>{
  1022. fs.writeFileSync('run.done', 'success')
  1023. }).catch(()=>{
  1024. fs.writeFileSync('run.done', 'error')
  1025. })
  1026. }).catch(()=>{
  1027. fs.writeFileSync('run.done', 'error')
  1028. })
  1029. // Antibiotic stewardship program.
  1030. // 1st use is fine.
  1031. // Max vials dispense
  1032. // 2nd use Pharmacy needs justification Form.
  1033. // Approval after a certain period of time.
  1034. }
  1035. , 'g' : ()=>{
  1036. if(processedArgs.h) {
  1037. console.log('elxr g [modelname] => generate a model named [modelname]');
  1038. console.log('elxr g => regenerate all known models');
  1039. return
  1040. }
  1041. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1042. // console.log('Starting directory: ' + process.cwd());
  1043. // try {
  1044. // child = child.on('close', () => { process.chdir(label) } );
  1045. // console.log('New directory: ' + process.cwd());
  1046. // }
  1047. // catch (err) {
  1048. // console.log('chdir: ' + err);
  1049. // }
  1050. // child.on('close', function(){
  1051. // var options = {
  1052. // shell : true
  1053. // , inherit : true
  1054. // // , cwd : '' + process.cwd
  1055. // // , env : process.env
  1056. // };
  1057. // nodeShellExec('git', ['init'], { inherit : true});
  1058. if(0){
  1059. // PB : TODO -- Special google chrome profile for tests etc.
  1060. nodeShellExec('pwd', { inherit : true});
  1061. //$ "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 1" http://localhost:4200/tests/index.html?grep=loopback
  1062. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1063. "--profile-directory=Profile 1"
  1064. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1065. }
  1066. // nodeShellExec('npm', ['init', '-y'], options);
  1067. // nodeShellExec('npm', ['init', '-y'], options);
  1068. // })
  1069. var g = {
  1070. 'client' : ()=>{
  1071. console.info('Creating new ember client named : ' + processedArgs._[2] ) ;
  1072. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1073. stdio: ['pipe', process.stdout, process.stderr],
  1074. inherit : true,
  1075. shell: true,
  1076. cwd : path.dirname(__dirname),
  1077. env: env
  1078. })
  1079. }
  1080. }
  1081. g[processedArgs._[1]]();
  1082. }
  1083. }
  1084. return op[label] ? op[label]() : null;
  1085. }
  1086. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  1087. // mysql -u root -p db_name < drop_all_tables.sql
  1088. var mysql = '../xampp/mysql/bin/mysql'
  1089. var mysqldump = '../xampp/mysql/bin/mysqldump'
  1090. // --runas
  1091. if(processedArgs.runas) {
  1092. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  1093. __runcmd('runas')
  1094. }
  1095. else __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  1096. function nodeShellExec() {
  1097. var args = Array.from(arguments);
  1098. var opts = args[2] = args[2] || {}
  1099. opts.title ? null : opts.title = `${args[0]} ${args[1] }`
  1100. const child = spawn(...arguments);
  1101. var p = new Promise(function(resolve, reject){
  1102. if(!opts.detached) {
  1103. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  1104. var success = true;
  1105. if(opts.stdio !== 'ignore') {
  1106. child.stdout.setEncoding('utf8');
  1107. child.stderr.setEncoding('utf8');
  1108. child.stdout.on('data', (chunk) => { chunk.trim() === '' ? null : messages.push(chunk); /* console.log('d: ' + chunk) */ });
  1109. child.on('error', (chunk) => { success = false; messages.push(chunk); /* console.error('e: ' + chunk) */ } );
  1110. child.stderr.on('data', (chunk) => { messages.push(chunk);
  1111. // console.error('stderr e: ' + chunk)
  1112. });
  1113. }
  1114. child.on('close', (code) => {
  1115. if(+code !== 0) success = false;
  1116. if(opts.stdio !== 'ignore') {
  1117. if(opts.runas){
  1118. var logEntry = { result: `${opts.title} exited with code ${code}`, messages : messages }
  1119. success ? logEntry.success = true : null;
  1120. fs.writeFileSync('run.log', ', ' + JSON.stringify(logEntry), {'flag':'a+'} )
  1121. }
  1122. else {
  1123. success ? console.log(['success : ' + ` ${opts.title} exited with code ${code}`]) : console.error([`error : ${opts.title} exited with code ${code}`])
  1124. // console.log( messages.join('') )
  1125. process.stdout.write( messages.join('') )
  1126. }
  1127. }
  1128. if(code !== 0) return reject(code)
  1129. resolve(messages)
  1130. });
  1131. }
  1132. else {
  1133. child.unref()
  1134. resolve(true);
  1135. }
  1136. });
  1137. p.process = child;
  1138. return p;
  1139. }