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

var prompt = function(choices, label, defaultchoice){ var prompt = function(choices, label, defaultchoice){
// prompt accepts either an array or an object as choices. // prompt accepts either an array or an object as choices.
var choices = choices || []; var choices = choices || [];
defaultchoice = defaultchoice || choices[0] || choices[Object.keys(choices)[0]]
return this.prompter.ask( 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 => { ).then(choice => {
// propName = promptable.interpret(propValue) // propName = promptable.interpret(propValue)
if(!choice) return defaultchoice || choices[0]; if(!choice) return defaultchoice || choices[0];

+ 195
- 149
index.js View File

}) })
.catch((e) => { .catch((e) => {
e.repo = repo; e.repo = repo;
if(errHandler) return errHandler(e)
if(errHandler) throw errHandler(e)
if (__isElevated) { if (__isElevated) {
fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' }) fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
} }
env: process.env env: process.env
, cwd: instanceroot + '/' + repo , cwd: instanceroot + '/' + repo
, runas: processedArgs.runas , runas: processedArgs.runas
, title: `'git', ${['config', '--replace-all', 'user.name', username].join(' ')}`
, title: `'git', ${['config', '--replace-all', 'user.name', selectedinstance.username].join(' ')}`
}) })
.then(() => { .then(() => {
if (__isElevated) { if (__isElevated) {
}) })
.catch(e => { .catch(e => {
e.repo = repo; e.repo = repo;
if(errHandler) return errHandler(e)
if(errHandler) throw errHandler(e)
if (__isElevated) { if (__isElevated) {
fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' }) fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
} }
clusterNodeInstance(selected) { var clusternodename = 'node01' clusterNodeInstance(selected) { var clusternodename = 'node01'
return __acquireConfig(selected, selected.username, clusternodename return __acquireConfig(selected, selected.username, clusternodename
, selected.instanceName + '-config-' + selected.node_env + `-${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 , 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. // 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 , 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) } , genericChessInstance(selected) { return __acquireConfig(selected) }
} }
})() })()


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

var acquireConfig = function(slections){ 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) return any(configPriority.map(cfg => { return function() { return configs[cfg](slections) } } ), true, true)
} }


} }
else process.exit() else process.exit()
}) })
console.error()
} }


if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${owner}/${configrepo}.git/' not found`))){ 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() else process.exit()
}) })
} }
console.warn(e) console.warn(e)
console.warn('Config acquisition failed.')
throw e; //('Config acquisition failed.')
} }


var successHandler = () => { var successHandler = () => {
ENV.NODE_ENV = selectedinstance.node_env; 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()) var launchpath = path.normalize(process.cwd())
return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(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(`launchpath = ${launchpath}`)
console.log(`thisscriptdir = ${thisscriptdir}`) console.log(`thisscriptdir = ${thisscriptdir}`)


} }
// promptkeys.runchoice = promptkeys.cmd ? 'c' : undefined // promptkeys.runchoice = promptkeys.cmd ? 'c' : undefined


function createChessInstance( cfg ){
return createInstance(cfg)
function createLocalChessInstance( cfg ){
// return createInstance(cfg)
reconfirm = getReconfirmAll()
var inst = {}; var inst = {};
var __new = Object.assign({}, __default, cfg) var __new = Object.assign({}, __default, cfg)
inst[cfg.node_env] = __new; return inst; inst[cfg.node_env] = __new; return inst;
} }


var detection_state = { var detection_state = {
didWeFindInstance : false
localInstanceDetected : false
} }


const https = require('https') const https = require('https')


function createInstance(selectedinstance) { function createInstance(selectedinstance) {


// http://try.gitea.io/api/v1/org/{org}/repos
console.dir(selectedinstance) 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( { // GITEA.repository.updateattributes( {
// hostname : server.host, protocol : server.protocol // hostname : server.host, protocol : server.protocol
} }


var skipprerequisites = false; 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() { var startElxr = function() {
const retaincount = 2 const retaincount = 2
var min = runtimestamp; var min = runtimestamp;
reconfirm = getReconfirmAll() reconfirm = getReconfirmAll()
} }


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

Loading…
Cancel
Save