555
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 49KB

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