Browse Source

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

production
AkshaThomas 3 years ago
parent
commit
0b168164cd
4 changed files with 2618 additions and 264 deletions
  1. 12
    6
      cliverse.js
  2. 2478
    202
      i.js
  3. 127
    56
      index.js
  4. 1
    0
      package.json

+ 12
- 6
cliverse.js View File

var cli = { var cli = {
nodeShellExec nodeShellExec
, get prompter() { , get prompter() {
const clii = readline.createInterface({ input: process.stdin, output: process.stdout });
clii.ask = function(q){
return new Promise((resolve, reject)=>{
clii.question(q, (answer)=>{ resolve(answer) })
})
var prompt_interface = {
ask : function(q){
// Needs to be serialized. Parallel asks are not possible.
const clii = readline.createInterface({ input: process.stdin, output: process.stdout });
return new Promise((resolve, reject)=>{
clii.question(q, (answer)=>{
clii.close();
resolve(answer)
})
})
}
} }
return clii
return prompt_interface
} }
, prompt , prompt
} }

+ 2478
- 202
i.js
File diff suppressed because it is too large
View File


+ 127
- 56
index.js View File

const cliargs = utils.cliargs; const cliargs = utils.cliargs;
const processedArgs = cliargs(process.argv.slice(2)); const processedArgs = cliargs(process.argv.slice(2));
console.dir(processedArgs) console.dir(processedArgs)
// PB : TODO -- defaults for valuless arguments if passed.
// Object.keys(processedArgs).forEach(a=>{
// if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {

// }
// })

var globSync = require('glob').sync; var globSync = require('glob').sync;


var ENV = Object.assign({}, process.env); // Shallow clone it. var ENV = Object.assign({}, process.env); // Shallow clone it.
} }
else { else {
// PB : TODO -- Rename op['runas'] to 'elevate' // PB : TODO -- Rename op['runas'] to 'elevate'
return op['runas']().then(() => { return true; })

var __runasresult = null;

return op['runas']().then((r) => { return __runasresult = r; })
.catch((e) => { .catch((e) => {
console.error(e) console.error(e)
}) })
.finally(() => { .finally(() => {
fs.unlinkSync('run.done')
if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done')
if (!processedArgs.runas) { return tasdef.regularpulltasks(); } if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
}) })
} }
} }
else { else {
console.warn('No branch was specified detecting from working client.') console.warn('No branch was specified detecting from working client.')
var pullCmd = gitops.getdiscoverbranchcmd(repo)
// First check if working client exits.
// if (existsSync(instanceroot + '/' + repo)) {
var pullCmd = gitops.getdiscoverbranchcmd(repo)
// }
// else performpull
} }
// var pullCmd = ['pullall', [], { cwd : repo }] // var pullCmd = ['pullall', [], { cwd : repo }]
if (useGitPull) pullCmd = ['git', ['pull'], { if (useGitPull) pullCmd = ['git', ['pull'], {
}) })
} }
, 'runas': () => { , 'runas': () => {

if(processedArgs.skipelevated) return Promise.resolve({ skipped : true });

console.log('Testing Elevation') console.log('Testing Elevation')


if (__isElevated) { if (__isElevated) {
// git remote equivalents... // git remote equivalents...
// git branch --set-upstream-to=elixir-unc/master master // git branch --set-upstream-to=elixir-unc/master master
// git push --set-upstream elixir-unc branch.. // git push --set-upstream elixir-unc branch..
, 'remote': (args) => {
// Subcommands!
if(!processedArgs.v) return false;

var serial_perform = (repo) => {
var options = { cwd: instanceroot + '/' + repo }
return [
['git', ['remote', '-v'], options]
]
}

var x = (args) => {
var tasq = () => {
// console.log(args)
return nodeShellExec.apply(null, args).catch(e => {
// We continue on failure.
console.error(tasq.toString())
})
}
tasq.toString = function(){
return JSON.stringify(args)
}
return tasq;
}

var perform = (dir) => {
return any(serial_perform(dir.name).map(x))
}

dirs(perform)
}

, 'remote set-url': (args) => { , 'remote set-url': (args) => {
// git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
var __args = { var __args = {
} }
var perform_git_seturl = (dir) => { var perform_git_seturl = (dir) => {
op['is-git-repo'](dir).then((logEntry) => { op['is-git-repo'](dir).then((logEntry) => {
any(serial_perform_git_seturl(dir.name).map(x))
return any(serial_perform_git_seturl(dir.name).map(x))
}).catch((e) => { }).catch((e) => {
// console.log('Failed : ' + dir.name) // console.log('Failed : ' + dir.name)
}) })
// Usage : // Usage :
// elxr pull -- Defaults to run config // elxr pull -- Defaults to run config


return elxr.getpulltask()()
return elxr.getpulltask(selectedinstance)()
} }
, 'isInstalled': () => { , 'isInstalled': () => {
return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => { return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
} }
, getpulltask(def){ , getpulltask(def){


def = def || {
def = (def ? (
def.requiresElevation = true,
def.reqularRepos = def.repos,
def.elevatedRepos = def.elevatedRunasRepos

) : false) || {
requiresElevation : true, requiresElevation : true,
reqularRepos : gitRepos, reqularRepos : gitRepos,
elevatedRepos : elevatedRunasRepos elevatedRepos : elevatedRunasRepos
} }

console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`) console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
console.dir(def) console.dir(def)


// The main elxr cli process // The main elxr cli process
function elxrworker() { function elxrworker() {
var subcommandlabels = { var subcommandlabels = {
remote : `remote ${processedArgs._[1]}`
remote : (`remote ${processedArgs._[1] || ''}`).trim()
} }


var __runcmd = function (label) { var __runcmd = function (label) {
Warning : Cannot locate your preferred configuration since it was not specified Warning : Cannot locate your preferred configuration since it was not specified
You should fork the default chess configuration to customize and make it You should fork the default chess configuration to customize and make it
your own instance with a named config as your own instance with a named config as
{{yourowninstancename}}-config-{{yourcurrentenvironment}}
{{yourowninstancename}}-config-{{yourchosenenvironment}}
And then run this tool as follows And then run this tool as follows
NODE_ENV={{yourenvironment}} elxr i {{yourowninstancename}}
NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
OR OR
Run this tool with the following command to use a quick start default. Run this tool with the following command to use a quick start default.
node elxr --default
elxr --default
OR OR
Choose the the option to create a new instance for you interactively.
Choose one of the options below to run interactively.


We will run your choice of default or create your own at the next prompt.
We will run your choice at the next prompt.
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
`)) `))
var prompt = cli.prompter; var prompt = cli.prompter;
q) Quit q) Quit
Default <= d Default <= d
: `).then((choice) => { : `).then((choice) => {
prompt.close();
if (choice && choice === 'd' || !choice) { if (choice && choice === 'd' || !choice) {
processedArgs._[0] = 'i' processedArgs._[0] = 'i'
selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess' selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
} }


return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) { return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
p1.close()
selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in' selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
}) })
}) })
else processedArgs._[0] = cmd else processedArgs._[0] = cmd
return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) { return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in' selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
p1.close()
}) })
}) })
}) })
chessinstances['current_run'] = { instanceName: selected.instanceName, node_env: selected.node_env } chessinstances['current_run'] = { instanceName: selected.instanceName, node_env: selected.node_env }
// Config from server always override merges into selection ecept for the current selection. // Config from server always override merges into selection ecept for the current selection.
selectedinstance = utils.assign(chessinstances[selected.instanceName][selected.node_env], selected, repomanifest) selectedinstance = utils.assign(chessinstances[selected.instanceName][selected.node_env], selected, repomanifest)
// chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' }) fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
// PB : TODO -- We should probably write the new server config also... // 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... selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
Object.defineProperty(this, 'reposerver', { Object.defineProperty(this, 'reposerver', {
value: reposerver, value: reposerver,
writable: false, writable: false,
configurable : true
configurable : true,
enumerable : true
}); });
return reposerver return reposerver
}) })
Object.defineProperty(this, 'reposerver', { Object.defineProperty(this, 'reposerver', {
value: reposerver, value: reposerver,
writable: false, writable: false,
configurable : true
configurable : true,
enumerable : true
}); });
return reposerver return reposerver
} }
() => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; }) () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
, () => prompt.ask(`git email : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; }) , () => prompt.ask(`git email : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
] ]
return any([any(steps), any(prompts)]).then(() => { prompt.close() })
return any([any(steps), any(prompts)])
} }
, installsteps: function () { , installsteps: function () {
return any([this.installcmd].map(callsheltask)) return any([this.installcmd].map(callsheltask))
Object.defineProperty(this, propName, { Object.defineProperty(this, propName, {
value: propValue, value: propValue,
writable: false, writable: false,
configurable : true
configurable : true,
enumerable : true
}); });
return propValue return propValue
}) })
// Object.defineProperty(this, propName, { // Object.defineProperty(this, propName, {
// value: propValue, // value: propValue,
// writable: false, // writable: false,
// configurable : true
// configurable : true,
// enumerable : true
// }) // })
// return propValue; // return propValue;
// } // }
, configurable : true , configurable : true
, enumerable : true
} }
} }


selectedinstance = Object.assign(detectedInstance, clioverrides); selectedinstance = Object.assign(detectedInstance, clioverrides);
var todo = Promise.resolve(true); var todo = Promise.resolve(true);
var promptkeys = { 'instanceName' : processedArgs._[1] }

var reconfirm = {
'instanceName' : selectedinstance['instanceName'] === 'chess'
}
var prompts = [];
var eachPrompt = function(k, i, a){
// No local instances config found. We use a default initialized instance available in selectedinstance
// Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
if(promptkeys[k] && selectedinstance[k] !== promptkeys[k] || promptkeys[k] === undefined && selectedinstance[k] === undefined
|| reconfirm[k]) {
prompts.push(async ()=>{
// PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
// We take a snapshot... Shallow.. !! If required deep should be used based on use case.
// If latest altered state is required we can reerence this directly.
// var asyncthis = Object.assign(this);
Object.defineProperty(selectedinstance, k, getPromptableAsyncPropDescriptor(k, choices[k], promptkeys[k] || selectedinstance[k] ));
return await selectedinstance[k]
})
}
delete promptkeys[k]
}
try { try {
chessinstances = acquirelocalinstances(selectedinstance); chessinstances = acquirelocalinstances(selectedinstance);
initinstances(chessinstances, selectedinstance) initinstances(chessinstances, selectedinstance)
}
catch (e) {
console.error(e)
// Basic keys that must be prompted and confirmed if not supplied as cmd line args.
// PB: TODO --- This should be cmd specific interpretation of location parameters !!!
var promptkeys = {
'instanceName' : processedArgs._[1]
}

var reconfirm = {
'instanceName' : true
var instanceNameChoices = new Set(Object.keys( chessinstances) )
instanceNameChoices.delete('current_run')
instanceNameChoices.add(selectedinstance['instanceName'])
if(promptkeys['instanceName']) instanceNameChoices.add(promptkeys['instanceName'])
var choices = {
'instanceName' : Array.from(instanceNameChoices)
, 'reposerver' : selectedinstance['reposervers']
} }


Object.keys(__interactve_promts).forEach(eachPrompt, __interactve_promts)
Object.keys(promptkeys).forEach(eachPrompt, promptkeys)
todo = any(prompts).then(()=>{ return selectedinstance })
}
catch (e) {
console.error(e) // Missing chessinstances is not an error...
// No local instances config found. We use a default initialized instance available in selectedinstance
// Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
initinstances(chessinstances, selectedinstance) initinstances(chessinstances, selectedinstance)
var instanceNameChoices = new Set(Object.keys( chessinstances) ) var instanceNameChoices = new Set(Object.keys( chessinstances) )
instanceNameChoices.delete('current_run') instanceNameChoices.delete('current_run')
instanceNameChoices.add(selectedinstance['instanceName']) instanceNameChoices.add(selectedinstance['instanceName'])
instanceNameChoices.add(promptkeys['instanceName'])
if(promptkeys['instanceName']) instanceNameChoices.add(promptkeys['instanceName'])
var choices = { var choices = {
'instanceName' : Array.from(instanceNameChoices) 'instanceName' : Array.from(instanceNameChoices)
, 'reposerver' : selectedinstance['reposervers'] , 'reposerver' : selectedinstance['reposervers']
} }

var prompts = [];
var eachPrompt = function(k, i, a){
if(selectedinstance[k] !== promptkeys[k] || promptkeys[k] === undefined || reconfirm[k]) {
prompts.push(async ()=>{
// PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
// We take a snapshot... Shallow.. !! If required deep should be used based on use case.
// If latest altered state is required we can reerence this directly.
// var asyncthis = Object.assign(this);
Object.defineProperty(selectedinstance, k, getPromptableAsyncPropDescriptor(k, choices[k], promptkeys[k] || selectedinstance[k] ));
return await selectedinstance[k]
})
}
delete promptkeys[k]
}

Object.keys(__interactve_promts).forEach(eachPrompt, __interactve_promts) Object.keys(__interactve_promts).forEach(eachPrompt, __interactve_promts)
Object.keys(promptkeys).forEach(eachPrompt, promptkeys) Object.keys(promptkeys).forEach(eachPrompt, promptkeys)
if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){ if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
// Weve been told what to do. // Weve been told what to do.
todo = acquireChoices(selectedinstance)
todo = todo.then(() => { return acquireChoices(selectedinstance) })
} }
todo = todo.then(() => { todo = todo.then(() => {
// 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 !!!
ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`) ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
if (!skipprerequisites && !__isElevated) mainTasks.push(verifyAndInstallPrerequisites);
if (!skipprerequisites && !__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
mainTasks.push(maintask) mainTasks.push(maintask)
return any(mainTasks); return any(mainTasks);
}) })

+ 1
- 0
package.json View File

"crossfilter2": "^1.5.4", "crossfilter2": "^1.5.4",
"chalk": "^4.1.0", "chalk": "^4.1.0",
"glob": "^7.1.2", "glob": "^7.1.2",
"uuid": "^8.3.2",
"tree-kill": "^1.2.2" "tree-kill": "^1.2.2"
}, },
"bin": { "bin": {

Loading…
Cancel
Save