Browse Source

elxr upgrades

master
pb 2 years ago
parent
commit
91df1649db
2 changed files with 216 additions and 68 deletions
  1. 5
    3
      cliverse.js
  2. 211
    65
      index.js

+ 5
- 3
cliverse.js View File

if(args.length > 1){ if(args.length > 1){
var opts = args[2] = args[2] || {} var opts = args[2] = args[2] || {}
opts.title ? null : opts.title = `${args[0]} ${args[1] }` opts.title ? null : opts.title = `${args[0]} ${args[1] }`
} }
else { else {
opts = {
var opts = {
title : `${args[0]}` title : `${args[0]}`
// , inherit: true, shell: true // , inherit: true, shell: true
} }
} }
opts.stdin = 'pipe';
// // const spawn = require('child_process').spawn; // // const spawn = require('child_process').spawn;
// const s = spawn( // const s = spawn(
// D:\chess\instances\elixir_01\elxr/.elxr/run-1630002739610/download.bat https://github.com/git-for-windows/git/releases/download/v2.33.0.windows.2/Git-2.33.0.2-64-bit.exe D:\\chess\\instances\\elixir_01\\elxr/Downloads/Git-2.33.0.2-64-bit.exe // D:\chess\instances\elixir_01\elxr/.elxr/run-1630002739610/download.bat https://github.com/git-for-windows/git/releases/download/v2.33.0.windows.2/Git-2.33.0.2-64-bit.exe D:\\chess\\instances\\elixir_01\\elxr/Downloads/Git-2.33.0.2-64-bit.exe
// D:\\chess\\instances\\elixir_01\\elxr/.elxr/run-1630002923584/download.bat https://github.com/git-for-windows/git/releases/download/v2.33.0.windows.2/Git-2.33.0.2-64-bit.exe D:\\chess\\instances\\elixir_01\\elxr/Downloads/Git-2.33.0.2-64-bit.exe // D:\\chess\\instances\\elixir_01\\elxr/.elxr/run-1630002923584/download.bat https://github.com/git-for-windows/git/releases/download/v2.33.0.windows.2/Git-2.33.0.2-64-bit.exe D:\\chess\\instances\\elixir_01\\elxr/Downloads/Git-2.33.0.2-64-bit.exe
const child = spawn(...args);
var p = new Promise(function(resolve, reject){ var p = new Promise(function(resolve, reject){
// console.log(...args) // console.log(...args)
const child = spawn(...args);
if(!opts.detached) { if(!opts.detached) {
var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks... var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
var success = true; var success = true;
resolve(true); resolve(true);
} }
}); });
// p.process = child;
p.process = child;
return p; return p;
} }



+ 211
- 65
index.js View File

const homedir = require('os').homedir(); const homedir = require('os').homedir();




function sysAddPathVar(path){
function sysAddPathVar(addpath){
// Object.assign({ // Object.assign({
// inherit: true, shell: true, env: ENV, title: `${command} ${args}` // inherit: true, shell: true, env: ENV, title: `${command} ${args}`
// }, options) // }, options)
// powershell $env:Path -split ';'
if (__isElevated) {
return nodeShellExec('Powershell.exe', [
`$path = [Environment]::GetEnvironmentVariable('PATH', 'Machine')
$newpath = $path + ';${addpath}'
[Environment]::SetEnvironmentVariable("PATH", $newpath, 'Machine')`
]).then(() => {
fs.writeFileSync('run.done', 'success')
}).catch(() => {
fs.writeFileSync('run.done', 'error')
})
}
else return op['runas']()
var newpath = path.split(';');
newpath = Array.from(new Set(newpath.push(path))).join(';')
// path.split(';').forEach(pel => { var kv = pel.split('='); kv[0] === key ? null : newpath.push(pel); } )
return nodeShellExec('setx', ['/m', 'PATH', newpath ]);
// var newpath = addpath.split(';');
// newpath.push(addpath)
// newpath = Array.from(new Set(newpath)).join(';')
// // addpath.split(';').forEach(pel => { var kv = pel.split('='); kv[0] === key ? null : newpath.push(pel); } )
// // setx /M PATH "%PATH%;<path-to-executable-folder>"
// // %AppData%\npm
// return nodeShellExec('setx', ['/m', 'PATH', `%PATH%;${addpath}` ]);
} }


// singleton one time lazy // singleton one time lazy
process.env.wd = process.cwd(); process.env.wd = process.cwd();
if(process.cwd() === __dirname) { if(process.cwd() === __dirname) {
// This script was launched in the same dir. // This script was launched in the same dir.
// We do not know if it was copied to some random location. Check if we have elxr installed in current location. Or subidr.
process.env.wd = path.dirname( process.env.wd ); // Default to the parent.
} }
} }
} }
return getshelltask(args)() return getshelltask(args)()
} }


var getCmdString = function(args){ return `"${args[0]} ${args[1].join(' ')}"` }

var getshelltask = (args) => { var getshelltask = (args) => {
return args[0] === 'rm' ? getgitbashtask(args) : () => { return nodeShellExec.apply(null, args) } } return args[0] === 'rm' ? getgitbashtask(args) : () => { return nodeShellExec.apply(null, args) } }
var getgitbashtask = (args) => { return () => {
return nodeShellExec( `"${gitbash}"`, ['-c', `"${args[0]} ${args[1].join(' ')}"`], args[2]) }
var getgitbashtask = (args, onEachError) => { return () => {
return nodeShellExec( `"${gitbash}"`, ['-c', getCmdString(args)], args[2]).catch( onEachError || function(e){ console.error(e) }) }
} }


var getTaskCheckExists = (command, options) => { var getTaskCheckExists = (command, options) => {
}).finally(statuslog.finally) }).finally(statuslog.finally)


} }
, 'start': (label) => {
console.log('Starting Elixir Server.');
var env = Object.assign({}, process.env); // Shallow clone it.
// console.dir(env)
env.NODE_ENV = process.env.NODE_ENV || 'development';
env.DEBUG = 'loopback:connector:' + dbForLabel(label)
var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
// cmd = 'node'
cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
var childPromise = nodeShellExec(...cmd, {
// inherit : true,
shell: true,
detached: true,
stdio: 'ignore',
cwd: instanceroot + '/' + 'elixir-server'
, env: env
})
, 'start': (args) => {


var child = childPromise.process;
if (typeof child.pid !== 'undefined') {
console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
encoding: 'utf8'
var label = clioverrides.cmd
var env = Object.assign({}, process.env); // Shallow clone it.
env.NODE_ENV = clioverrides.node_env || 'development';
var nodecmd = clioverrides.node_env === 'development' ? 'nodemon' : 'node';
function startFn( o ){
var cmd = [nodecmd, [`--inspect=${o.debugport}`, '--preserve-symlinks', o.script]]
console.log(`Starting ${o.name}.`);
var childPromise = nodeShellExec('cmd', ['/k', getCmdString(cmd) ], {
// inherit : true,
shell: true,
detached: true,
stdio: 'ignore',
cwd: instanceroot + o.path
, env: env
}) })
var child = childPromise.process;
var cpid = child.pid
if (typeof child.pid !== 'undefined') {
childPromise.then(()=>{
console.log(` *** started Elixir Loopback Server PID(${cpid}) : NODE_ENV=${clioverrides.node_env} ${cmd}`);
fs.writeFileSync('.elixir-server.elixir.server.pid', '' + cpid)
})
.catch(e => console.errror(e) )
}
} }


if(clioverrides.node_env === 'development') {
env.DEBUG = 'loopback:connector:' + dbForLabel(label)
startFn( { debugport : 9228, script : 'elixir/server.js', name : 'Elixir Loopback Server', path : '/' + 'elixir-server' } )
startFn( { debugport : 9227, script : 'bin/www', name : 'Express Server', path : '/' + 'chess-server-lib/server' } )
// cmd = 'node'()

// nodeShellExec('node', ['--inspect=9226', ' bin/www'], { // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
// inherit : true, // inherit : true,
// shell: true, detached: true, // shell: true, detached: true,
// cwd : 'client/', // cwd : 'client/',
// env: env // env: env
// }) // })
console.log('Starting Elixir Client Host.');
var cmd = ['ember', ['s']]
var childPromise = nodeShellExec(...cmd, {
// var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
// PB : TODO -- ember debugging.
// inherit : true,
shell: true,
detached: true,
stdio: 'ignore',
cwd: instanceroot + '/' + 'client'
, env: env
})
// .catch(e=>console.error(e))
// console.log('Starting Elixir Client Host.');
// var cmd = ['ember', ['s']]
// var childPromise = nodeShellExec(...cmd, {
// // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
// // PB : TODO -- ember debugging.
// // inherit : true,
// shell: true,
// detached: true,
// stdio: 'ignore',
// cwd: instanceroot + '/' + 'client'
// , env: env
// })
// // .catch(e=>console.error(e))


child = childPromise.process;
if (typeof child.pid !== 'undefined') {
console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
fs.writeFileSync('.client.server.pid', child.pid, {
encoding: 'utf8'
})
// child = childPromise.process;
// if (typeof child.pid !== 'undefined') {
// console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
// fs.writeFileSync('.client.server.pid', child.pid, {
// encoding: 'utf8'
// })
// }
} }

} }
, 'stop': (label) => { , 'stop': (label) => {
const kill = require('tree-kill'); const kill = require('tree-kill');
console.log(serverPid) console.log(serverPid)
kill(serverPid) kill(serverPid)


serverPid = fs.readFileSync('.client.server.pid', {
serverPid = fs.readFileSync('.express.server.pid', {
encoding: 'utf8' encoding: 'utf8'
}) })
fs.unlinkSync('.client.server.pid')
fs.unlinkSync('.express.server.pid')
console.log(serverPid) console.log(serverPid)
kill(serverPid) kill(serverPid)
} }
, switch : (`switch ${processedArgs._[1] || ''}`).trim() , switch : (`switch ${processedArgs._[1] || ''}`).trim()
} }


var independentcmd = function(){
return false;
}

var cmds = { var cmds = {
remote : { remote : {
// return a interpreted set of arguments for this comd run context. // return a interpreted set of arguments for this comd run context.
return { cmd : subcommandlabels['remote'], runchoice : 'c' } return { cmd : subcommandlabels['remote'], runchoice : 'c' }
} }
} }
, resetgitconfig : {
// return a interpreted set of arguments for this comd run context.
cmdFn : resetgitconfig
, interpret() { return { cmd : 'resetgitconfig' } }
, getPossiblePrompts(){ return {} }
, noprerequisites : true
, independentcmd : true
}
, reinit : {
// return a interpreted set of arguments for this comd run context.
cmdFn : reinit
, interpret() { return { cmd : 'reinit' } }
, getPossiblePrompts(){ return {} }
, noprerequisites : true
, independentcmd : true
, requiresElevation : true
, requires : [ generateDependencies ]
}
, switch : { , switch : {
interpret() { interpret() {
return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2] return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2]
, commonInstance(selected) { return __acquireData(selected, defaultRepoOwner , commonInstance(selected) { return __acquireData(selected, defaultRepoOwner
// , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') } // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
) } ) }
, genericChessInstance(selected) { return __acquireData(selected) }
} }
})() })()


return any(configPriority.map(cfg => { return function() { return instanceData[cfg](slections) } } ), true, true) return any(configPriority.map(cfg => { return function() { return instanceData[cfg](slections) } } ), true, true)
} }


// Git Credential storage...
// notepad C:/Program Files/Git/etc/gitconfig
// git config --global --unset credential
// git config --edit --system
// git config --global credential.helper "store --file ~/gitcredentials"
// git credential fill
// git credential-store --file ~/git.store store

function reinit(){
sysAddPathVar('%AppData%\\npm')
resetgitconfig()
}


function resetgitconfig(){
// https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage
// Git Credential storage...
// git config --global credential.helper 'store --file ~/.gitcredentials'
// git credential-store --file ~/.gitcredentials store
// // notepad C:/Program Files/Git/etc/gitconfig
// git config --global --unset credential
// git config --edit --system
// git config --global credential.helper "store --file ~/gitcredentials"
// git credential fill
// git credential-store --file ~/git.store store
// Find system git config
// git config --global --edit
// git config --list --show-origin
// git config --list --show-origin --show-scope
// https://stackoverflow.com/questions/35942754/how-can-i-save-username-and-password-in-git
// Recipie
// git config --global --unset credentials.helper
// cd /path/to/my/repo
// git config --unset credential.helper
// git config credential.helper 'store --file ~/.git_repo_credentials'
// git config credential.*.username my_user_name
// git config credential.https://gitlab.com.username my_user_name
// git credential fill
// git config --global credential.modalprompt false // doesnst work.
// core askpass = ;;; https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows
var options = {
inherit: true, shell: true //, env: process.env
, cwd: instanceroot
, runas: processedArgs.runas
}
var task = ['git', ['config'], options]

var tasklist = [
// ['--global', '--unset credentials.helper']
// ['--unset', 'credentials.helper']
// ,
// ['credential.helper', `'store --file git_repo_credentials'`]
['--global', 'credential.helper', "'store --file ~/.git_repo_credentials'"]
, ['--global', '--replace-all', 'user.name', 'pb']
, ['--global', '--replace-all', 'user.email', 'pradeep@bbh.org.in']

// , ['--list']
// , ['credential', 'fill']
]
var onEachError = e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n')
var shellT = (args) => { return getgitbashtask(args, onEachError)
// .catch(e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n' + tasq.toString()) )
}
execserial(tasklist, task, shellT, onEachError )
}

var createTasq = (args, shellT, onEachError) => {
var tasq = shellT ? shellT(args) : (() => { return nodeShellExec.apply(null, args).catch( onEachError || function(e){ console.error(e) } ) })
tasq.toString = function(){ return JSON.stringify(args)}
return tasq;
}

var execserial = function(tasklist, task, shellT){
var exec = (taskArgs)=>{
var thistask = task.concat();
thistask[1] = thistask[1].concat()
thistask[1].push.apply(thistask[1], taskArgs)
return createTasq(thistask, shellT)
}

return any(tasklist.map(exec))
}

var execone = function(taskArgs, task){ return any([task[1].push.apply(task[1], taskArgs)].map(createTasq)) }


var __acquireConfig = function (selected, owner, clusternodename, configrepo, errHandler) { var __acquireConfig = function (selected, owner, clusternodename, configrepo, errHandler) {


configrepo = configrepo || selected.instanceName + '-config-' + selected.node_env; configrepo = configrepo || selected.instanceName + '-config-' + selected.node_env;
return function(){ return function(){
return hasElxr(p).then((value)=>{ return hasElxr(p).then((value)=>{
if(value) return p if(value) return p
// PB : TODO -- Using throw like this is not friendly with any...
throw { value : false }; throw { value : false };
}) })
} }
var tasks = [ var tasks = [
'/elxr' // Is there a subfolder named elxr '/elxr' // Is there a subfolder named elxr
, '/elxr/.git' // which is self git repository , '/elxr/.git' // which is self git repository
, '/elxr/.elxr' // and has .elxr subfolder
, '/elxr/.elxr/' + __ALIAS__STAMP__ // Which has our stamp.
// , '/elxr/.elxr' // and has .elxr subfolder we now store this in the instanceroot.
, '/elxr/' + __ALIAS__STAMP__ // Which has our stamp.
] ]


if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{ if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{




// function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) } // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
var selectedinstance = null;
var selectedinstance = { root : process.env.wd };
var chessinstances = { current_run : {} }; var chessinstances = { current_run : {} };
var promptkeys = { var promptkeys = {
cmd : processedArgs._[0] || 'pull' cmd : processedArgs._[0] || 'pull'


} }


var generateDependencies = function(){
function generateDependencies(){
// PB : TODO -- Keep only the last n runs... // PB : TODO -- Keep only the last n runs...
// Currently it retains 2*n when proc needs to be relaunched in elevated mode !!! // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!


} }


detectInstanceRoot.then(()=>{ detectInstanceRoot.then(()=>{
return acquireElevationState().then(() => {
return startElxr()
var cmdobj = cmds[clioverrides.cmd]
return Promise.all((cmdobj.requires || []).map( (r) => utils.promisify(null, r) ) ).then(()=>{
if(cmdobj.independentcmd) {
if(cmdobj.requiresElevation) {
return acquireElevationState().then(() => {
cmdobj.cmdFn() })
}
else return cmdobj.cmdFn()
}
else return acquireElevationState().then(() => {
return startElxr()
})
})
.catch(e => {
console.log('error ')
}) })
}) })



Loading…
Cancel
Save