|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567 |
-
- // --------------
- // elxr
- // A cli tool for elixr.
- const { existsSync } = require('fs');
- const fs = require('fs')
- const { spawn, spawnSync } = require('child_process');
- const cliargs = require('../elxr/cliargs'); // Use minimist...
- const processedArgs = cliargs(process.argv.slice(2));
- console.dir(processedArgs)
-
- var path = require('path')
- // Serialize a set of functions that will execute to return a promises one after the other.
- // Will stop when any one fails.
- function any(iterable, continueOnFailure) {
- return iterable.reduce(
- (p, fn, i ,a) => {
- // console.log('accumulator :');
- // console.log(p);
- if(Promise.resolve(p) === p ) {
- return p.then((pVal) => {
-
- if(Promise.resolve(pVal) === pVal) {
- // Passed in function retured a promise. We still need to wait for it.
- pVal.then((pVal)=>{
-
- // console.log('Then --pVal = ' + pVal + ' bContinue = ' + continueOnFailure ); console.log(p);
- if(!pVal && !continueOnFailure) {
- console.error("E : pVal :" + pVal);
- // i==0 ? null : console.error("E :1 a[i-1] " + a[i-1]);
- // a.map((i)=>console.error(i.toString()));
- console.error('debugData 3 -------------------');
- // console.error(debugData);
- console.error('debugData 3 -------------------');
-
- console.log("Cancelling remaining...");
- throw 'Failed in reduce 1 '
- return false;
- }
- // console.log('calling fn : '+ fn);
- return (Promise.resolve(fn) === fn ) ? fn : fn() ;
- })
- }
- else {
-
- // console.log('Then --pVal = ' + pVal + ' bContinue = ' + continueOnFailure ); console.log(p);
- if(!pVal && !continueOnFailure) {
- console.error("E : pVal :" + pVal);
- // i==0 ? null : console.error("E :1 a[i-1] " + a[i-1]);
- // a.map((i)=>console.error(i.toString()));
- console.error('debugData 3 -------------------');
- // console.error(debugData);
- console.error('debugData 3 -------------------');
-
- console.log("Cancelling remaining...");
- throw 'Failed in reduce 1 '
- return false;
- }
- // console.log('calling fn : '+ fn);
- return (Promise.resolve(fn) === fn ) ? fn : fn() ;
- }
-
-
-
- }).catch((error) => {
- console.error("E : " + error);
- fn ? console.error("Fn : " + fn.toString()) : null;
- // i==0 ? null : console.error("E :2 a[i-1] " + a[i-1]);
- // a.map((i)=>console.error(i.toString()));
- console.error('debugData 4-------------------------');
- // console.error(debugData);
- console.error('debugData 4-------------------------');
-
- throw 'Failed in reduce 2 '
- return false;
- })
- }
- else if(!p) {
- console.log("Bypass on failure");
- return false;
- }
- }
- , Promise.resolve(true)
- );
- }
-
- var isRunningElevated = ()=>{
- return nodeShellExec( "fsutil", ["dirty", "query", "C:"], {
- inherit : true, shell: true
- , env: process.env
- , title : `check privileged execution mode using fsutil dirty query C:`
- }).then((exitcode)=>{
- console.log('Elevated')
- return true;
- }).catch(()=>{
- console.log('Not Elevated');
- throw false;
- });
- }
-
-
- var cli = 'elxr';
- var ver = '#unversioned';
- var help = '#unkown list of commands... please refer dveloper documentation for ' + cli;
-
- // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
-
-
- // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
-
- var dbForLabel = function(label){
- var dbsForLabel = {
- devmysql : 'mysql'
- , development : 'mssql'
- , production : 'mssql'
- }
- return dbsForLabel[label] || 'mysql'
- }
-
- // Relevant git repos
- var gitRepos = [
- 'ember-masonry-grid'
- , 'bbhverse'
- , 'clientverse'
- , 'serververse'
- , 'client'
- // , 'client/server'
- , 'elxr'
- , 'elixir-client'
- , 'elixir-client-unlinked'
- , 'ember-searchable-select'
- , 'loopback-component-jsonapi'
- , 'elixir-config'
- , 'cihsr-config'
- , 'cihsr-data'
- , 'elixir-data'
- , 'loopback-connector-ds'
- , 'chess-server-lib'
- , 'setup'
- ]
-
- // Repositiories that have symlinks that required elevated priviletes in windows to create symlinks
- //
- var elevatedRunasRepos = [
- 'elixir-server'
- , 'cihsr-server'
- , 'chess-server'
- ]
-
-
- var env = Object.assign({}, process.env); // Shallow clone it.
- var __runcmd = function(label){
-
- var op = {
- 'h' : ()=>{ console.log(cli + ' ' + ver + ' ' + help); return '-h' }
- , 'upgrade' : ()=>{
- console.log('upgrade.......')
- var tasks = [
- ()=>{
- var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
- inherit : true, shell: true
- , env: process.env
- }).catch((e)=>{ console.error(e) })
- p.position = 1;
- console.log('One')
- return p;
- }
- , ()=>{
- var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
- inherit : true, shell: true
- , env: process.env
- }).catch((e)=>{ console.error(e) })
-
- p.position = 2;
- console.log('Two')
- return p;
- }
- , ()=>{
- var p = nodeShellExec('npm', ['install', '-g', 'n'], {
- inherit : true, shell: true
- , env: process.env
- }).catch((e)=>{ console.error(e) })
- p.position = 3;
- console.log('Three')
- return p;
- }
- , ()=>{
- var p = nodeShellExec('n', ['latest'], {
- inherit : true, shell: true
- , env: process.env
- }).catch((e)=>{ console.error(e) })
- p.position = 4;
- console.log('Four')
- return p;
- }
- ]
- any(tasks)
- console.log('.......done')
- console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
- console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
- console.info('Uninstalling existing ember globally') ;
- var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
- stdio: ['pipe', process.stdout, process.stderr],
- inherit : true,
- shell: true,
- cwd : path.dirname(__dirname),
- env: env
- })
- step1.on('close', ()=>{
- console.info('Installing ember globally') ;
- var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
- stdio: ['pipe', process.stdout, process.stderr],
- inherit : true,
- shell: true,
- cwd : path.dirname(__dirname),
- env: env
- })
-
- step2.on('close', ()=>{
- nodeShellExec('cmd', ['/c', 'ember', '--version'], {
- stdio: ['pipe', process.stdout, process.stderr],
- inherit : true,
- shell: true,
- cwd : path.dirname(__dirname),
- env: env
- })
- })
- })
- }
- , 'runas' : ()=>{
- return isRunningElevated().then(
- () => op[ processedArgs.label || processedArgs._[0] || 'h']()
- )
- .catch(()=>{
- console.log('Not Elevated');
- console.log('Requesting Elevated Privileges')
- nodeShellExec('MSHTA', [`javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('node', 'elxr ${processedArgs._[0]} ${processedArgs._[1]} ${processedArgs._[2]} --runas=true', '', 'runas', 1);close();`]
- , {
- // inherit : true
- // , shell: true
- env: process.env
- , title : `runas`
- }
- );
- })
- }
- , 'push' : ()=>{
- if(!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
- // init remote bare from local
- // pushandinitremotebare
- // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
- // connect to repo server -- net use 172.16.0.27
- // cd 172.16.0.27/repos/
- // mkdir repo.git
- // cd repo.git
- // git init --bare
- // cd localrepo
- // git remote rename origin githubclone
- // git remote add origin //172.16.0.27/repos/repo.git
- // git push origin master
-
- var repo = processedArgs._[1];
- var defaultRepoServer = '//172.16.0.27/repos'
-
- var sequentialTaskShellCommands = [];
- if(!existsSync(`Z:/${repo}.git`)){
- sequentialTaskShellCommands = [
- // ['net', ['use', 'Z:', defaultRepoServer.replace('/','\\')], {
- // inherit : true, shell: true
- // , env: process.env
- // }]
- ['pwd', { cwd : 'Z:', inherit : true}]
- , ['mkdir', [`${repo}.git`], {
- cwd : `Z:`
- , inherit : true, shell: true
- , env: process.env
- }]
- , ['pwd', { cwd : `Z:/${repo}.git`, inherit : true}]
- , ['git', ['init', '--bare'], { cwd : `Z:/${repo}.git`
- , inherit : true, shell: true
- , env: process.env
- }]
- , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd : `${repo}`}] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
- , ['git', ['remote', 'add', 'origin', `${defaultRepoServer}/${repo}.git`], { cwd : `${repo}`}]
- ]
- if(!existsSync(`Z:`)){
- sequentialTaskShellCommands.splice(0,0, ['net', ['use', 'Z:', defaultRepoServer.replace(/\//gm,'\\')], {
- inherit : true, shell: true
- , env: process.env
- }])
- console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
- // throw 'done'
- }
- }
-
- sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd : `${repo}`}])
- // console.dir(sequentialTaskShellCommands);
-
- var tasks = [];
- sequentialTaskShellCommands.forEach(shellcmd => {
- // console.log(shellcmd)
- tasks.push(()=>{
- var p = nodeShellExec.apply(null, shellcmd).catch((e)=>{ console.error(e) })
- return p;
- })
- })
- any(tasks);
-
- }
- , 'pull' : (label) => {
- var env = Object.assign({}, process.env); // Shallow clone it.
- // console.dir(env)
- console.log('Running exlr pull : ' + path.dirname(__dirname))
- // nodeShellExec('cmd', ['/c', 'setup\\utility\\chess.bat', 'pull'], {
- // // nodeShellExec('cmd', ['/c', '..\\setup\\utility\\chess.bat', 'pull'], {
- // stdio: ['pipe', process.stdout, process.stderr],
- // inherit : true,
- // shell: true,
- // cwd : path.dirname(__dirname),
- // env: env
- // })
-
- var performPull = repo => {
- if(existsSync(repo)) {
- console.log('pulling ' + repo)
- nodeShellExec('git', ['pull'], {
- inherit : true, shell: true,
- cwd : repo
- // , env: process.env
- , title : `git pull ${repo}`
- }).catch((e)=>{ console.error(e) })
- }
- else {
- console.log('cloning ' + repo)
- nodeShellExec('git', ['clone', '//172.16.0.27/repos/' + repo + '.git'],
- {
- inherit : true, shell: true,
- env: process.env
- , title : `git clone ${'//172.16.0.27/repos/' + repo + '.git'}`
- }).catch((e)=>{ console.error(e) })
- }
- }
-
- if(!processedArgs.runas) gitRepos.forEach(performPull)
- return isRunningElevated().then(
- ()=> elevatedRunasRepos.forEach(performPull))
- .catch(
- () => op['runas']()
- )
-
- }
- , 'npmi' : ()=>{
- var tasks = [];
- gitRepos.forEach(repo => {
-
- console.log('npm i for ' + repo)
- // nodeShellExec('pwd', [], {
- // // inherit : true, shell: true
- // cwd : repo
- // // , env: process.env
- // , title : `pwd for ${repo}`
- // }).catch((e)=>{ console.error(e) })
- nodeShellExec('rm', ['package-lock.json'], {
- inherit : true, shell: true
- , cwd : repo
- , env: process.env
- , title : `rm 'package-lock.json' for ${repo}`
- }).catch((e)=>{ console.error(e) })
- tasks.push(()=>{
- var p = nodeShellExec('npm', ['i'], {
- inherit : true, shell: true
- , cwd : repo
- , env: process.env
- , title : `npm i for ${repo}`
- }).catch((e)=>{ console.error(e) })
- return p;
- })
- })
- any(tasks);
-
- }
- , 'start' : (label)=>{
- console.log('Starting Elixir Server.');
- var env = Object.assign({}, process.env); // Shallow clone it.
- // console.dir(env)
- env.NODE_ENV = label || 'development';
- env.DEBUG = 'loopback:connector:' + dbForLabel(label)
-
- nodeShellExec('node', ['--inspect=9228', 'elixir/server.js'], {
- // inherit : true,
- shell: true, detached: true,
- cwd : 'elixir-server',
- env: env
- })
-
- // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
- // inherit : true,
- // shell: true, detached: true,
- // cwd : 'qms/server',
- // env: env,
- // shell : true
- // })
-
- nodeShellExec('ember', ['s'], {
- // inherit : true,
- shell: true, detached: true,
- cwd : 'client/',
- env: env
- })
- }
- , 'use' : ()=>{
-
- if(!processedArgs.runas){
- try {
- var runconfig = require('./run.js')
- if(processedArgs._[1] && runconfig.use === processedArgs._[1]) {
- return;
- }
- else runconfig.use = processedArgs._[1];
- fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
- }
- catch(e) {
- runconfig = { use : processedArgs._[1] };
- fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
- }
- op['runas']()
- }
- else {
- var runconfig = require('../run.js')
- console.log('runconfig.use : ' + runconfig.use)
- var tasks = [
- ()=>{
- var p = nodeShellExec('rm', ['config'], {
- inherit : true, shell: true
- , cwd : repo
- , env: process.env
- , title : `rm 'package-lock.json' for ${repo}`
- }).catch((e)=>{ console.error(e) })
- return p;
- },
- ()=>{
- var p = nodeShellExec('rm', ['data'], {
- inherit : true, shell: true
- , cwd : repo
- , env: process.env
- , title : `rm 'package-lock.json' for ${repo}`
- }).catch((e)=>{ console.error(e) })
- return p;
- },
- ()=>{
- var p = nodeShellExec('mklink', ['/D', 'data', runconfig.use + '-data'], {
- inherit : true, shell: true
- , env: process.env
- }).catch((e)=>{ console.error(e) })
- return p;
- },
- ()=>{
- var p = nodeShellExec('mklink', ['/D', 'config', runconfig.use + '-config'], {
- inherit : true, shell: true
- , env: process.env
- }).catch((e)=>{ console.error(e) })
- return p;
- }
- ]
- any(tasks)
- }
-
-
- // Antibiotic stewardship program.
- // 1st use is fine.
- // Max vials dispense
- // 2nd use Pharmacy needs justification Form.
- // Approval after a certain period of time.
- }
- , 'g' : ()=>{
- if(processedArgs.h) {
-
- console.log('elxr g [modelname] => generate a model named [modelname]');
- console.log('elxr g => regenerate all known models');
- return
- }
- // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
- // console.log('Starting directory: ' + process.cwd());
- // try {
- // child = child.on('close', () => { process.chdir(label) } );
- // console.log('New directory: ' + process.cwd());
- // }
- // catch (err) {
- // console.log('chdir: ' + err);
- // }
- // child.on('close', function(){
- // var options = {
- // shell : true
- // , inherit : true
- // // , cwd : '' + process.cwd
- // // , env : process.env
- // };
- // nodeShellExec('git', ['init'], { inherit : true});
- if(0){
- // PB : TODO -- Special google chrome profile for tests etc.
- nodeShellExec('pwd', { inherit : true});
- //$ "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 1" http://localhost:4200/tests/index.html?grep=loopback
- nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
- "--profile-directory=Profile 1"
- , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
-
- }
- // nodeShellExec('npm', ['init', '-y'], options);
- // nodeShellExec('npm', ['init', '-y'], options);
- // })
-
- var g = {
- 'client' : ()=>{
- console.info('Creating new ember client named : ' + processedArgs._[2] ) ;
- var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
- stdio: ['pipe', process.stdout, process.stderr],
- inherit : true,
- shell: true,
- cwd : path.dirname(__dirname),
- env: env
- })
- }
- }
- g[processedArgs._[1]]();
- }
- }
- return op[label] ? op[label]() : op['start'](label);
- }
-
- // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
- // mysql -u root -p db_name < drop_all_tables.sql
-
- var mysql = '../xampp/mysql/bin/mysql'
- var mysqldump = '../xampp/mysql/bin/mysqldump'
-
- __runcmd(processedArgs.label || processedArgs._[0] || 'h');
- // nodeShellExec('git', ['status']);
-
- function nodeShellExec() {
-
- var args = Array.from(arguments);
- args[2] ? null : args[2] = {}
- args[2].title ? null : args[2].title = `${args[0]} ${args[1]}`
- const child = spawn(...arguments);
-
- return new Promise(function(resolve, reject){
- var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
-
- // use child.stdout.setEncoding('utf8'); if you want text chunks
- child.stdout.setEncoding('utf8');
- child.stderr.setEncoding('utf8');
- child.stdout.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
- child.on('error', (chunk) => { messages.push(chunk); /*console.error(chunk)*/ });
- child.stderr.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
- // child.stderr.pipe(process.stderr);
-
- child.on('close', (code) => {
-
- console.log([` ${args[2].title} exited with code ${code}`])
- // console.log([ messages.join('') ])
- process.stdout.write( messages.join('') )
- if(code !== 0 ) return reject(code)
- resolve(true)
- });
- });
- }
-
|