Browse Source

Merge branch 'master' of http://git.bbh.org.in/chess/elxr

master
Aksha Thomas 3 years ago
parent
commit
b5327c176f
2 changed files with 197 additions and 150 deletions
  1. 2
    1
      cliverse.js
  2. 195
    149
      index.js

+ 2
- 1
cliverse.js View File

@@ -92,8 +92,9 @@ function nodeShellExec() {
var prompt = function(choices, label, defaultchoice){
// prompt accepts either an array or an object as choices.
var choices = choices || [];
defaultchoice = defaultchoice || choices[0] || choices[Object.keys(choices)[0]]
return this.prompter.ask(
`${label} \n` + Object.keys(choices).map(choice => { return ` ${(+choice) + 1}) ${choices[choice]} `}).join('\n') + `\n default ( <= ${ defaultchoice || choices[0]} ) : `
`${label} \n` + Object.keys(choices).map(choice => { var choice_label = isNaN(+choice) ? choice : ((+choice) + 1); return ` ${choice_label}) ${choices[choice]} `}).join('\n') + `\n default ( <= ${ defaultchoice || choices[0]} ) : `
).then(choice => {
// propName = promptable.interpret(propValue)
if(!choice) return defaultchoice || choices[0];

+ 195
- 149
index.js View File

@@ -294,7 +294,7 @@ var performPull = (repo, branch, repoowner, errHandler) => {
})
.catch((e) => {
e.repo = repo;
if(errHandler) return errHandler(e)
if(errHandler) throw errHandler(e)
if (__isElevated) {
fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
}
@@ -320,7 +320,7 @@ var performPull = (repo, branch, repoowner, errHandler) => {
env: process.env
, cwd: instanceroot + '/' + repo
, runas: processedArgs.runas
, title: `'git', ${['config', '--replace-all', 'user.name', username].join(' ')}`
, title: `'git', ${['config', '--replace-all', 'user.name', selectedinstance.username].join(' ')}`
})
.then(() => {
if (__isElevated) {
@@ -338,7 +338,7 @@ var performPull = (repo, branch, repoowner, errHandler) => {
})
.catch(e => {
e.repo = repo;
if(errHandler) return errHandler(e)
if(errHandler) throw errHandler(e)
if (__isElevated) {
fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
}
@@ -2246,23 +2246,30 @@ var configs = (function(){
clusterNodeInstance(selected) { var clusternodename = 'node01'
return __acquireConfig(selected, selected.username, clusternodename
, selected.instanceName + '-config-' + selected.node_env + `-${clusternodename}`
, function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.') }
, function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
return e; }
)
}
, ownerInstnace(selected) { return __acquireConfig(selected, selected.username, null, null
, function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.') }
, function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
return e }
)
}
// PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
, commonInstance(selected) { return __acquireConfig(selected, defaultRepoOwner
// , function(e){ console.info('This is an error prompt choices.') }
// , 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 __acquireConfig(selected) }
}
})()

var eNotImplemented = function(){
console.error('Not yet implemented')
process.exit()
}

var acquireConfig = function(slections){
var configPriority = [ 'clusterNodeInstance', 'ownerInstnace', 'commonInstance', 'genericChess' ]
var configPriority = [ 'clusterNodeInstance', 'ownerInstnace', 'commonInstance', 'genericChessInstance' ]
return any(configPriority.map(cfg => { return function() { return configs[cfg](slections) } } ), true, true)
}

@@ -2284,25 +2291,40 @@ var __acquireConfig = function (selected, owner, clusternodename, configrepo, er
}
else process.exit()
})
console.error()
}

if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${owner}/${configrepo}.git/' not found`))){
return cli.prompt( ['(i) install new instance with this name locally'
, '(f) fork a new instance for yourself'
, '(c) customize your personal instance for this node'
, '(e) exit']
, 'Config for instance not found. Would you like to with this name ? (y/n) ', 'y' ).then(propValue => {
if(propValue === 'y') {
return createLocalChessInsance()
}
var choices = {
t : `install a new temporary local instance with this name ( will not persist ).
Use your own username for additional options. You can request for a username at chess@bbh.org.in )`
, e : 'exit' }

if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
choices = utils.assign({
i : 'create a new instance with this name => will fork the default config under your username'
, f : 'fork a new instance with this name for yourself for this node from another instance'
, o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
, c : 'create a custom config for yourself for this node' // prompt hostname as nodename
, p : 'create a custom config for yourself '
}, choices)
}

return cli.prompt( choices
, 'Config for instance not found. Would you like to ', 'e' ).then(propValue => {
if(propValue === 't') return createInstance()
if(propValue === 'i') return eNotImplemented()
if(propValue === 'f') return eNotImplemented()
if(propValue === 'o') return eNotImplemented()
if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
// if(propValue === 'o') createChessInstance(selectedinstance, orgname)
else process.exit()
})
}
console.warn(e)
console.warn('Config acquisition failed.')
throw e; //('Config acquisition failed.')
}

var successHandler = () => {
@@ -2326,8 +2348,14 @@ var __acquireConfig = function (selected, owner, clusternodename, configrepo, er
ENV.NODE_ENV = selectedinstance.node_env;
}

return performPull(configrepo, null, owner, errHandler || ((e)=>{ throw e })).then( successHandler )
.catch( errorHandler )
return performPull(configrepo, null, owner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
.catch( (e)=>{
// if(e){
if(Promise.resolve(e) === e) return e;
console.error(e)
throw e; // Not a hard error but we need this for bcontinueonfailure
// }
})
}

var launchpath = path.normalize(process.cwd())
@@ -2475,7 +2503,7 @@ var detectfromroot = function(root){
return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(root) ) }
}
var detectinstances = function () {
var detectLocalInstances = function () {
console.log(`launchpath = ${launchpath}`)
console.log(`thisscriptdir = ${thisscriptdir}`)

@@ -3060,8 +3088,9 @@ var promptkeys = {
}
// promptkeys.runchoice = promptkeys.cmd ? 'c' : undefined

function createChessInstance( cfg ){
return createInstance(cfg)
function createLocalChessInstance( cfg ){
// return createInstance(cfg)
reconfirm = getReconfirmAll()
var inst = {};
var __new = Object.assign({}, __default, cfg)
inst[cfg.node_env] = __new; return inst;
@@ -3105,7 +3134,7 @@ var getInteractionPoints = function(detectedinstanceoptions, possiblePrompts, pr
}

var detection_state = {
didWeFindInstance : false
localInstanceDetected : false
}

const https = require('https')
@@ -3287,23 +3316,40 @@ const GIT = (function(){

function createInstance(selectedinstance) {

// http://try.gitea.io/api/v1/org/{org}/repos
console.dir(selectedinstance)
var server = new URL(selectedinstance.reposerver);
return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
, username : selectedinstance.username, password : selectedinstance.password
}
// , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
, { repo : `chess-config`, owner : 'chess' }, {}, function( repository ){
return GITEA.repository.updateattributes( {
hostname : server.host, protocol : server.protocol
, username : selectedinstance.username, password : selectedinstance.password
}
, { repo : `chess-config`, owner : selectedinstance.username }
, { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
)
}
)
if(selectedinstance.local) {
selectedinstance
var args = {
remotebase : selectedinstance.reposerver + '/chess/'
, sourcerepo : 'chess-config'
, targetrepo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`
}

cmdseq = ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]

return any(cmdseq.map(getshelltask)).then(() => {
return true
})
}
else {
// http://try.gitea.io/api/v1/org/{org}/repos
var server = new URL(selectedinstance.reposerver);
return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
, username : selectedinstance.username, password : selectedinstance.password
}
// , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
, { repo : `chess-config`, owner : 'chess' }, {}, function( repository ){
return GITEA.repository.updateattributes( {
hostname : server.host, protocol : server.protocol
, username : selectedinstance.username, password : selectedinstance.password
}
, { repo : `chess-config`, owner : selectedinstance.username }
, { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
)
}
)
}
// GITEA.repository.updateattributes( {
// hostname : server.host, protocol : server.protocol
@@ -3317,124 +3363,124 @@ function createInstance(selectedinstance) {
}

var skipprerequisites = false;
function initinstances(selected_overrides) {
var root = selected_overrides.root // We should always have this coz we are running at some place which is fixed by detectinstances.
function initinstances(selected_overrides) {
var root = selected_overrides.root // We should always have this coz we are running at some place which is fixed by detectLocalInstances.

var instanceName = selected_overrides.instanceName
|| clioverrides.instanceName
// || processedArgs._[1]
|| chessinstances.current_run.instanceName
var node_env = selected_overrides.node_env
|| clioverrides.node_env
// || processedArgs.node_env
|| chessinstances.current_run.node_env

var reposerver = selected_overrides.reposerver
|| clioverrides.reposerver
// || processedArgs.node_env
|| chessinstances.current_run.reposerver
var instanceName = selected_overrides.instanceName
|| clioverrides.instanceName
// || processedArgs._[1]
|| chessinstances.current_run.instanceName
if(!instanceName) {
promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
}
var node_env = selected_overrides.node_env
|| clioverrides.node_env
// || processedArgs.node_env
|| chessinstances.current_run.node_env

var reposerver = selected_overrides.reposerver
|| clioverrides.reposerver
// || processedArgs.node_env
|| chessinstances.current_run.reposerver
if(!node_env) {
promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
}
if(!instanceName) {
promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
}

if(!reposerver) {
promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
}
if(!node_env) {
promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
}

chessinstances[instanceName] = chessinstances[instanceName] || createChessInstance( {
instanceName, node_env, root : selected_overrides.root, reposerver : promptkeys['reposerver'] } );
chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root }
if(!reposerver) {
promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
}

if(path.normalize(selected_overrides.root) !== path.normalize(chessinstances[instanceName][node_env].root)) {
throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selected_overrides.root
}
// Override sequence.
// __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
selectedinstance = utils.assign(
chessinstances[instanceName][node_env]
, clioverrides
, selected_overrides
// , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
);
chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
instanceName, node_env, root : selected_overrides.root, reposerver : selected_overrides.reposerver /* promptkeys['reposerver'] */ } );
chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root }

// chessinstances[instanceName] = chessinstances[instanceName] || {}
// chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
// if(!selectedinstance.repos || selectedinstance.instanceName) {
// // Brand New.
// selectedinstance = Object.assign( __default, selectedinstance )
// }
if(!selectedinstance.repos[0].repo) {
console.warn('repo manifest has obsolete format. Attempting upgrade.')
selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
}
if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
}
// Config from server always override merges into selection except for the current selection.
// PB : TODO -- utils.assign Array merges are non-distinct...
chessinstances[instanceName][node_env] = selectedinstance;
// chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
cacheWriteInstanceConfig(chessinstances)
// PB : TODO -- We should probably write the new server config also...
selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
if(path.normalize(selected_overrides.root) !== path.normalize(chessinstances[instanceName][node_env].root)) {
throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selected_overrides.root
}
// Override sequence.
// __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
selectedinstance = utils.assign(
chessinstances[instanceName][node_env]
, clioverrides
, selected_overrides
// , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
);

return chessinstances
// chessinstances[instanceName] = chessinstances[instanceName] || {}
// chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
// if(!selectedinstance.repos || selectedinstance.instanceName) {
// // Brand New.
// selectedinstance = Object.assign( __default, selectedinstance )
// }
if(!selectedinstance.repos[0].repo) {
console.warn('repo manifest has obsolete format. Attempting upgrade.')
selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
}
if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
}
var skipprereqs = {}
var maintask = () => {
// Default cmd to run !
processedArgs._[0] === processedArgs._[0] || 'pull';
// selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.

if(!noprerequisites[processedArgs._[0]]
&& !skipprereqs[processedArgs._[0]]
) {
return prerequisites.git.verifyAndInstall().then(()=>{
var e = { message : 'verifyAndInstall', success : true}
var inittasks = []
if(!detection_state.didWeFindInstance) {
inittasks.push(createInstance(selectedinstance).then(() => { preworkerconfig(); return elxrworker(true) }))
}
else {
inittasks.push(acquireConfig(selectedinstance).catch((err) => {
e = err;
console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
console.error(err)
}).then(() => { preworkerconfig(); return elxrworker(true) })
// .finally(()=>{
// fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
// if(!e.success) fs.writeFileSync('run.done', 'error');
// // return process.exit()
// }))
)
}
return any(inittasks)
})
}
else {
console.log('cmd has no preqs or has been configured to skip preqs')
preworkerconfig()
return elxrworker()
}
// Config from server always override merges into selection except for the current selection.
// PB : TODO -- utils.assign Array merges are non-distinct...
chessinstances[instanceName][node_env] = selectedinstance;
// chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
cacheWriteInstanceConfig(chessinstances)
// PB : TODO -- We should probably write the new server config also...
selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...

return chessinstances
}

var skipprereqs = {}
var maintask = () => {
// Default cmd to run !
processedArgs._[0] === processedArgs._[0] || 'pull';
// selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.

if(!noprerequisites[processedArgs._[0]]
&& !skipprereqs[processedArgs._[0]]
) {
return prerequisites.git.verifyAndInstall().then(()=>{
var e = { message : 'verifyAndInstall', success : true}
var inittasks = []
if(!detection_state.localInstanceDetected) {
inittasks.push(createInstance(selectedinstance).then(() => { preworkerconfig(); return elxrworker(true) }))
}
else {
inittasks.push(acquireConfig(selectedinstance).catch((err) => {
e = err;
console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
console.error(err)
}).then(() => { preworkerconfig(); return elxrworker(true) })
// .finally(()=>{
// fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
// if(!e.success) fs.writeFileSync('run.done', 'error');
// // return process.exit()
// }))
)
}
return any(inittasks)
})
}
else {
console.log('cmd has no preqs or has been configured to skip preqs')
preworkerconfig()
return elxrworker()
}

}

var startElxr = function() {
const retaincount = 2
var min = runtimestamp;
@@ -3444,7 +3490,7 @@ var startElxr = function() {
reconfirm = getReconfirmAll()
}

return detectinstances().then((detectedinstanceoptions)=>{
return detectLocalInstances().then((detectedinstanceoptions)=>{
detectedinstanceoptions.splice(0,0, __default)
@@ -3464,7 +3510,7 @@ var startElxr = function() {
initinstances(selectedinstance) // use the local instances for defaults if at all possible.
var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
var inst = initinstances(selectedinstance)
detection_state.didWeFindInstance = true;
detection_state.localInstanceDetected = true;
return inst;
})
}
@@ -3485,7 +3531,7 @@ var startElxr = function() {
findlocalinstances(chessinstances, detectedinstanceoptions)
detectedinstanceoptions.splice(0,0, __default)
initinstances(selectedinstance)
detection_state.didWeFindInstance = true;
detection_state.localInstanceDetected = true;
}
catch (e) {
// console.error(e)
@@ -3495,7 +3541,7 @@ var startElxr = function() {
// // selectedinstance = Object.assign(detectedInstance, clioverrides);
// return selectedinstance = Object.assign(__default, selectedinstance);
// })
detection_state.didWeFindInstance = false;
detection_state.localInstanceDetected = false;
return selectedinstance
}
})

Loading…
Cancel
Save