Browse Source

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

production
aaron 3 years ago
parent
commit
c1b126d4d8
4 changed files with 650 additions and 258 deletions
  1. 12
    5
      cliverse.js
  2. 170
    63
      i.win.js
  3. 468
    186
      index.js
  4. 0
    4
      rollup.config.js

+ 12
- 5
cliverse.js View File

}); });
} }
child.on('close', (code) => { child.on('close', (code) => {
console.log('Proper close was fired')
// console.log('Proper close was fired')
var logEntry = { code, success } var logEntry = { code, success }
if(+code !== 0 || opts.haserrors) { success = false; logEntry = { result: `${opts.title} exited with code ${code}`, success, code }}; if(+code !== 0 || opts.haserrors) { success = false; logEntry = { result: `${opts.title} exited with code ${code}`, success, code }};
if(opts.stdio !== 'ignore') { if(opts.stdio !== 'ignore') {
} }


var prompt = function(choices, label, defaultchoice){ var prompt = function(choices, label, defaultchoice){
var choices = choices || [];
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 => { return ` ${(+choice) + 1}) ${choices[choice]} `}).join('\n') + `\n default ( <= ${ defaultchoice || choices[0]} ) : `
).then(choice => { ).then(choice => {
// propName = promptable.interpret(propValue)
if(!choice) return defaultchoice || choices[0]; if(!choice) return defaultchoice || choices[0];
if(choice && isNaN(+choice)) return choice; if(choice && isNaN(+choice)) return choice;
return choices[(+choice) - 1]; return choices[(+choice) - 1];
const clii = readline.createInterface({ input: process.stdin, output: process.stdout }); const clii = readline.createInterface({ input: process.stdin, output: process.stdout });
return new Promise((resolve, reject)=>{ return new Promise((resolve, reject)=>{
clii.question(q, (answer)=>{ clii.question(q, (answer)=>{
clii.close();
console.log("resolve is being called");
resolve(answer)
try {
clii.close();
console.log("readline.createInterface closed");
resolve(answer)
}
catch(e) {
reject(e)
}
}) })
}) })
} }

+ 170
- 63
i.win.js View File



var __Promise = {}; var __Promise = {};
// if(!String.prototype.trim) String.prototype.trim = function(){
// return this.replace(/^\s+|\s+$/g, '');
// };

// var ovrrides = { // var ovrrides = {
// resolve : function(v){ // resolve : function(v){
// if(v && v.then) return v; // if(v && v.then) return v;
} }
var runtimestamp = (new Date()).getTime(); var runtimestamp = (new Date()).getTime();


var promises = [];
function startPromises(){
promises.forEach(function(p){
// console.log(p.chain)
p();
// promises.splice(0,1)
})
}

function isWin(){ return /^win/.test(process.platform) }

try{ try{
__Promise = Promise __Promise = Promise
var __require = require
var map = Array.map
// -------------------------------------------- // --------------------------------------------
// Node Exists. Lets launch ourselves in Node itself // Node Exists. Lets launch ourselves in Node itself
var selectedinstance = { root : path.resolve(".") } var selectedinstance = { root : path.resolve(".") }
__main(selectedinstance) __main(selectedinstance)
} }
// catch(e){}
catch(e){ catch(e){
// // -------------------------------------------- // // --------------------------------------------
// // Cscript // // Cscript
var wsh = true; var wsh = true;
function isWin(){ return true; }
// If UCase( Right( WScript.FullName, 12 ) ) = "\CSCRIPT.EXE" Then // If UCase( Right( WScript.FullName, 12 ) ) = "\CSCRIPT.EXE" Then


var clii = { var clii = {
} }
var shell = new ActiveXObject('shell.application'); var shell = new ActiveXObject('shell.application');
var promises = [];
promises.forEach = forEach promises.forEach = forEach
function startPromises(){ function startPromises(){
promises.forEach(function(p){ promises.forEach(function(p){
var shellExec = function(cmd, argstr){ var shellExec = function(cmd, argstr){
var objShell = WScript.createobject("wscript.shell") var objShell = WScript.createobject("wscript.shell")
// console.log(argstr.join( ' '))
var oExec = objShell.Exec(cmd + ' ' + argstr.join(' ')) var oExec = objShell.Exec(cmd + ' ' + argstr.join(' '))
var result = {} var result = {}
var shellresult = { shell : objShell, result : result } var shellresult = { shell : objShell, result : result }
var WshFinished = 1 var WshFinished = 1
var WshFailed = 2 var WshFailed = 2
while(oExec.Status === WshRunning){ while(oExec.Status === WshRunning){
WScript.StdOut.write('.')
WScript.StdOut.write('s.')
WScript.Sleep(500) WScript.Sleep(500)
} }
var strOutput = ''
var strOutput = '\n'
switch(oExec.Status) { switch(oExec.Status) {
case WshFinished : case WshFinished :
strOutput = oExec.StdOut.ReadAll() strOutput = oExec.StdOut.ReadAll()
} }
result.result = command + ' ' + cargs + ' exited with code ' + result.code result.result = command + ' ' + cargs + ' exited with code ' + result.code
result.messages = [strOutput] result.messages = [strOutput]
// console.log(strOutput)
// WScript.Echo(oExec.Status) // WScript.Echo(oExec.Status)
// WScript.Echo(oExec.ProcessID) // WScript.Echo(oExec.ProcessID)
// WScript.Echo(oExec.ExitCode) // WScript.Echo(oExec.ExitCode)


// console.log(objShell.StdOut.ReadAll) // console.log(objShell.StdOut.ReadAll)
// console.log(objShell.StdErr.ReadAll) // console.log(objShell.StdErr.ReadAll)

// objShell = WScript.createobject("wscript.shell")
objShell = null;
return shellresult; return shellresult;
} }


var p = null; var p = null;
var pworker = function(resolve, reject){ var pworker = function(resolve, reject){
// console.dir(p) // console.dir(p)
var pfx = selectedinstance.root + '/.elxr/run-' + runtimestamp + '/' + stampedFilePfx(new Date())
var pfx = selectedinstance.root + '\\.elxr\\run-' + runtimestamp + '\\' + stampedFilePfx(new Date())
// console.log('p.chain.length ================ ' + p.chain.length) // console.log('p.chain.length ================ ' + p.chain.length)
options = options || { options = options || {
runFile : path.normalize( pfx + "out.txt") runFile : path.normalize( pfx + "out.txt")
// runFile : null // runFile : null
} }
var runFile = null; var runFile = null;
// var runFile = options.runFile
// var runFile = selectedinstance.root + '\\' + stampedFilePfx(new Date()) + command + cargs + "out.txt";
var runFile = options.runFile || pfx + command + cargs + "out.txt";
// console.log(runFile) // console.log(runFile)
var args = cargs.concat() var args = cargs.concat()
// runFile ? (args.push(">"), args.push(runFile)) : cargs // runFile ? (args.push(">"), args.push(runFile)) : cargs


var runbat = path.normalize(pfx + "run.bat") var runbat = path.normalize(pfx + "run.bat")
// console.log('runbat : ' + runbat) // console.log('runbat : ' + runbat)
fs.writeFileSync(runbat, command + ' ' + args.join(' ') + ' \r\n' + 'echo done > ' + runFile )
fs.writeFileSync(runbat,
'@echo off \r\n' +
(options.cwd ? 'cd ' + options.cwd + ' \r\n' : '') +
// ' cmd /k notepad.exe \r\n' +
command + ' ' + args.join(' ') + ' \r\n' +
'cmd /c echo done >> ' + runFile + ' \r\n' +
'echo done'
)
// fs.writeFileSync(runFile, 'started') // fs.writeFileSync(runFile, 'started')
// WScript.Quit() // WScript.Quit()
// elevatedshellexecute(runFile) // elevatedshellexecute(runFile)
// // cmd /b /c // // cmd /b /c
// }, 500) } // }, 500) }


console.log(options.waitmsg || ('awaiting ' + command + ' ' + args.join(' '))) console.log(options.waitmsg || ('awaiting ' + command + ' ' + args.join(' ')))
var shellresult = shellExec( 'cmd', [ '/c', runbat])
// var shellresult = shellExec( 'cmd', ['/c', runbat]) // var shellresult = shellExec( 'cmd', ['/c', runbat])
var shellresult = shellExec( command, args)
// var shellresult = shellExec( command, args)
var wrapup = function(result) { var wrapup = function(result) {
// console.log('Wrapping up') // console.log('Wrapping up')
try { try {
// console.log('resolving.....................');
// console.log('--------------P' + result.messages.join(' ').trim() +'P--------------')
// if(result.messages.join().trim()) resolve(result)
// else reject(result)
resolve(result) resolve(result)
} }
catch(e){ catch(e){
// console.dir(e) // console.dir(e)
if(e.message === 'Input past end of file') { if(e.message === 'Input past end of file') {
// console.log('resolving'); console.dir(result)
// console.log('---------------------------------------')
// console.dir(result)
resolve(result) resolve(result)
} }
else { else {
// console.dir(e)
reject(e) reject(e)
} }
} }
} }


if(runFile){
var waitr = function(){
WScript.StdOut.write('.')
if(existsSync(runFile)) {
var strOutput = fs.readFileSync(runFile)
shellresult.result.messages = [strOutput]
wrapup(shellresult.result)
sfs.unlinkSync(runFile)
}
wait( waitr, 500)
}
// console.log(wait)
// if(runFile){
// var waitr = function(){
// WScript.StdOut.write('w.')
// if(existsSync(runFile)) {
// var strOutput = fs.readFileSync(runFile)
// shellresult.result.messages = [strOutput]
// wrapup(shellresult.result)
// fs.unlinkSync(runFile)
// }
// // console.dir(shellresult.result)
// wait( waitr, 500)
// }
// // console.log(wait)
wait( waitr, 500)
}
else {
// wait( waitr, 500)
// }
// else {
// console.log('There is no runfile.') // console.log('There is no runfile.')
// console.log(shellresult.strOutput) // console.log(shellresult.strOutput)
wrapup(shellresult.result) wrapup(shellresult.result)
}
// }
} }
p = new Promise(pworker) p = new Promise(pworker)
// promises.push(p) // promises.push(p)
p.chain.push(thenfn) p.chain.push(thenfn)
return p; return p;
} }
, pcatch : function(catchfn) {
, 'catch' : function(catchfn) {
catchfn.isCatch = true catchfn.isCatch = true
p.chain.push(catchfn) p.chain.push(catchfn)
return p; return p;
, resolve : resolve , resolve : resolve
, processchain : processchain , processchain : processchain
} }

p['catch'] = p['pcatch']
p.chain.forEach = forEach; p.chain.forEach = forEach;
return p; return p;
} }
var runFile = path.normalize(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/' + stampedFilePfx(new Date()) + 'where' + command + "out.txt"); var runFile = path.normalize(selectedinstance.root + '/.elxr/run-' + runtimestamp + '/' + stampedFilePfx(new Date()) + 'where' + command + "out.txt");
var p = nodeShellExec.apply(null, ['cmd', ['/c', 'where', command], { runFile : runFile } ]) var p = nodeShellExec.apply(null, ['cmd', ['/c', 'where', command], { runFile : runFile } ])
p.runFile = runFile; p.runFile = runFile;
var catchr = 'catch'
// console.log(p['catch'])
if(p['catch']) { catchr = 'catch' } else { catchr = 'pcatch';}
if (options.ignorefailures) { if (options.ignorefailures) {
return p.then(function(v) { return p.then(function(v) {
// WScript.Echo('firstThen ' + v); // WScript.Echo('firstThen ' + v);
return v })[catchr]( function(e) {
return v })['catch']( function(e) {
console.error(e); console.error(e);
// Ignore. Not a major error if where command fails !!! // Ignore. Not a major error if where command fails !!!
throw e; throw e;
// return decision // return decision
// } // }


// prereq definition helpers. We can't do proper inheritance in cscript. So fallback to global functions.
function exists(next){
var self = this;
console.log('checking existence of ' + self.shellcmd)
return getTaskCheckExists(self.shellcmd, { ignorefailures: true })().then(function(exists) {
// console.log('-------------exists=======================')
// console.dir(exists)
// console.log(exists + ' ' + self.shellcmd + ' exists')
if(exists && exists.messages.join(' ').indexOf(self.shellcmd) > -1 ) {
return true;
}
else return false
})['catch'](function(e){
// console.log('-------------exists catch=======================')
console.dir(e)
return false;
})
}


var prerequisites = [ var prerequisites = [
{ {
shellcmd: 'git', shellcmd: 'git',
var self = this; var self = this;
console.log('Git Installsteps called') console.log('Git Installsteps called')
var ifns = [self.installcmd] var ifns = [self.installcmd]
ifns.map = map;
if(!ifns.map) ifns.map = map;
return any(ifns.map(callsheltask))['catch'](function(e){ return any(ifns.map(callsheltask))['catch'](function(e){
if(e.code === 1602) { if(e.code === 1602) {
console.warn("Installation was probably cancelled.") console.warn("Installation was probably cancelled.")
, ['git', ['config', '--global', '--add', 'user.email', gitEmail]] , ['git', ['config', '--global', '--add', 'user.email', gitEmail]]
] ]
steps.map = map;
if(!steps.map) steps.map = map;
return any(steps.map(callsheltask)).then(function(){ return any(steps.map(callsheltask)).then(function(){


}) })
else return self.install(); else return self.install();
}) })
} }
, exists : function(next){
var self = this;
return getTaskCheckExists(self.shellcmd, { ignorefailures: true })().then(function(exists) {
// console.dir(exists)
// console.log(exists + ' git exists')
if(exists && exists.messages.join(' ').indexOf(self.shellcmd) > -1 ) {
return true;
}
else return false
})
}
, exists : exists
, getUser : function(repo, onNoResult){ , getUser : function(repo, onNoResult){
if(!repo) globalOrLocal = '--global'; if(!repo) globalOrLocal = '--global';
else globalOrLocal = '--local' else globalOrLocal = '--local'
var fns = [['git', ['config', globalOrLocal, '--get-all', 'user.name']]] var fns = [['git', ['config', globalOrLocal, '--get-all', 'user.name']]]
fns.map = map;
if(!ifns.map) ifns.map = map;
return any(fns.map(callsheltask)).then(function(result){ return any(fns.map(callsheltask)).then(function(result){
// not yet configured. // not yet configured.
if(!result.success) return onNoResult() if(!result.success) return onNoResult()
else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection ! else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
} }
}) })
.pcatch(function(e){
['catch'](function(e){
console.log(e) console.log(e)
return onNoResult() return onNoResult()
}) })
, install : function() { , install : function() {
var self = this; var self = this;
var ifns = [self.installcmd] var ifns = [self.installcmd]
ifns.map = map;
if(!ifns.map) ifns.map = map;
return any(ifns.map(callsheltask))['catch'](function(e){ return any(ifns.map(callsheltask))['catch'](function(e){
if(e.code === 1602) { if(e.code === 1602) {
console.warn("Installation was probably cancelled.") console.warn("Installation was probably cancelled.")
}) })
} }
, exists : function(next){
var self = this;
return getTaskCheckExists(self.shellcmd, { ignorefailures: true })().then(function(exists) {
// console.log(self.shellcmd + ' ' + exists + ' node exists')
if(exists && exists.messages.join(' ').indexOf(self.shellcmd) > -1 ) {
return true
}
else {
// console.log(self.shellcmd + ' ' + exists + ' node doesnt exist')
return false
}
})
}
, exists : exists
, preinstallsteps: function() { , preinstallsteps: function() {
var self = this; var self = this;
console.log('Node preinstall steps') console.log('Node preinstall steps')
// return any([any(steps), any(prompts)]) // return any([any(steps), any(prompts)])
} }
} }
,
{
shellcmd: 'elxr'
, installcmd: [ isWin() ? 'npm.cmd' : 'npm' , ['link'], { cwd : selectedinstance.root + '\\elxr' /* cwd should be the cloned dir*/}]
, preinstallsteps: function() {
var self = this;
console.log('Elxr preinstall steps')

var steps = [];
steps.push(
function(){
console.log('Elxr PreInstallsteps called')
var ifns = [ ['git', ['clone', 'http://git.bbh/chess\\elxr'] ] ]
if(existsSyncFolder( selectedinstance.root + '\\elxr')) {
if(existsSyncFolder( selectedinstance.root + '\\elxr\\.git')) {
// PB : TODO -- use a elxr guid signature to detect more reliably folders named the same that is not us.
ifns = [ ['git', ['pull'], { cwd : selectedinstance.root + '\\elxr' } ] ]
}
else {
throw 'elxr subfolder not recognized as a git repository. Please cleanup and continue.'
}
}
else console.log(selectedinstance.root + '\\elxr' + ' NOT FOUND ')
if(!ifns.map) ifns.map = map;
return any(ifns.map(callsheltask))['catch'](function(e){
if(e.code === 1602) {
console.warn("Installation was probably cancelled.")
}
else throw e
})
}
)
return any([any(steps)])
}
, installsteps: function () {
var self = this;
console.log('Elxr Installsteps called')
var ifns = [self.installcmd]
if(!ifns.map) ifns.map = map;
return any(ifns.map(callsheltask))['catch'](function(e){
if(e.code === 1602) {
console.warn("Installation was probably cancelled.")
}
else throw e
})
}
, install: function () {
var self = this;
console.log('Elxr Install called')
return any([ /*self.preinstallsteps,*/ function(){ return self.installsteps() } ])
}
// , exists : function(){
// console.log('Elxr PreInstallsteps called')
// var ifns = [ ['git', ['clone', 'http://git.bbh/chess\\elxr'] ] ]
// if(existsSyncFolder( selectedinstance.root + '\\elxr')) {
// if(existsSyncFolder( selectedinstance.root + '\\elxr\\.git')) {
// // PB : TODO -- use a elxr guid signature to detect more reliably folders named the same that is not us.
// ifns = [ ['git', ['pull'], { cwd : selectedinstance.root + '\\elxr' } ] ]
// }
// else {
// throw 'elxr subfolder not recognized as a git repository. Please cleanup and continue.'
// }
// }
// else console.log(selectedinstance.root + '\\elxr' + ' NOT FOUND ')
// if(!ifns.map) ifns.map = map;
// return any(ifns.map(callsheltask))['catch'](function(e){
// if(e.code === 1602) {
// console.warn("Installation was probably cancelled.")
// }
// else throw e
// })
// }
, exists : exists
}
] ]


if(!prerequisites.forEach) prerequisites.forEach = forEach; if(!prerequisites.forEach) prerequisites.forEach = forEach;
// , downloadsdir + '/' + 'Git-2.32.0.2-64-bit.exe']).start() // , downloadsdir + '/' + 'Git-2.32.0.2-64-bit.exe']).start()
promises.push(verifyAndInstallPrerequisites()) promises.push(verifyAndInstallPrerequisites())


if(wsh) startPromises();
startPromises();
} }



+ 468
- 186
index.js View File

var chalk = require('chalk') var chalk = require('chalk')




const __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b'
const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]'; const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
const runtimestamp = (new Date()).getTime(); const runtimestamp = (new Date()).getTime();
function getVersion() { return BUILD_VERSION; } function getVersion() { return BUILD_VERSION; }
console.log(getVersion())
console.log(getVersion());




// 'use strict'; // 'use strict';


// support runas lauched directly from shell. // support runas lauched directly from shell.
// pass in environment in hta to shellexecute. // pass in environment in hta to shellexecute.


// PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
(function () {
"use strict";
if (!Array.prototype.earlyreduce) {
Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
var iterable = this;
var donecallback = donecallback || (a=>a)
var result = { value : initialValue === undefined ? iterable[0] : initialValue };
initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
// function *earlyReduceGenerator(acc, v, i, a) {
for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
var element = iterable[i]
result = eachcallback(result, element, i, iterable)
if(result.done) return donecallback(result)
}
// }
return donecallback(result)
}
}
}());

const { existsSync } = require('fs'); const { existsSync } = require('fs');
const existsFolderSync = existsSync;
const fs = require('fs') const fs = require('fs')


const cliargs = utils.cliargs; const cliargs = utils.cliargs;
// } // }
// }) // })


var clioverrides = { }
processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
processedArgs.node_env ? clioverrides.node_env = processedArgs.node_env
: (process.env.NODE_ENV && process.env.NODE_ENV.trim())
? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) : null;

Object.keys(clioverrides).forEach( prop => { })

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.


var getShellTask = (command, args, options) => { var getShellTask = (command, args, options) => {
options = options || {} options = options || {}
var callshell = command === 'rm' ? callgitbashtask : callsheltask;
return () => { return () => {
var p = nodeShellExec.apply(null, [command, args, Object.assign({
inherit: true, shell: true, env: ENV, title: `${command} ${args}`
}, options)
var p = callshell( [command, args, Object.assign({
inherit: true, shell: true, env: ENV, title: `${command} ${args}`
}, options)
]) ])
if (options.ignorefailures) { if (options.ignorefailures) {
return p.catch(e => { return p.catch(e => {
} }
} }


var callsheltask = (args) => { return () => { return nodeShellExec.apply(null, args) } }
var callsheltask = (args) => {
return args[0] === 'rm' ? callgitbashtask(args) : () => { return nodeShellExec.apply(null, args) } }
var callgitbashtask = (args) => { return () => { var callgitbashtask = (args) => { return () => {
return nodeShellExec( `"${gitbash}"`, ['-c', `"${args[0]} ${args[1].join(' ')}"`], args[2]) } return nodeShellExec( `"${gitbash}"`, ['-c', `"${args[0]} ${args[1].join(' ')}"`], args[2]) }
} }



var getTaskCheckExists = (command, options) => { var getTaskCheckExists = (command, options) => {
options = options || {} options = options || {}
return () => { return () => {
// () => { // () => {
// console.log(`--rm package-lock.json for ${repodef.repo}--------------------`) // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
// return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], { // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
nodeShellExec('rm', ['package-lock.json'], {
(callShellTask(['rm', ['package-lock.json'], {
inherit: true, shell: true inherit: true, shell: true
, cwd: instanceroot + '/' + repodef.repo , cwd: instanceroot + '/' + repodef.repo
, env: process.env , env: process.env
, title: `rm 'package-lock.json' for ${repodef.repo}` , title: `rm 'package-lock.json' for ${repodef.repo}`
})
}]))()
.then(()=>{ .then(()=>{
console.log(`--rm package-lock.json for ${repodef.repo}--------------------`) console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
}).catch((e) => { console.error(e) }) }).catch((e) => { console.error(e) })
function acquireChoices(selectedinstance) { function acquireChoices(selectedinstance) {


var hasconfig = false; var hasconfig = false;
console.warn(chalk.yellow(`
console.warn(chalk.cyan(`
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
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
} }
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.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
}) })
}) })
}) })
selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } }) selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
} }
chessinstances[selected.instanceName][selected.node_env] = selectedinstance = utils.assign(selected, selectedinstance) chessinstances[selected.instanceName][selected.node_env] = selectedinstance = utils.assign(selected, selectedinstance)
chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
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...
cacheWriteInstanceConfig(chessinstances) cacheWriteInstanceConfig(chessinstances)
ENV.NODE_ENV = selectedinstance.node_env; ENV.NODE_ENV = selectedinstance.node_env;
}) })
} }


var launchpath = process.cwd().replace(/\\/, '/')
var thisscriptdir = __dirname
var instanceroot = launchpath;
var detectInstance = function () {
console.log(`launchpath = ${launchpath}`)
console.log(`thisscriptdir = ${thisscriptdir}`)

var root = launchpath;

// We need a reference to the root director for elxr cli to be properly oriented.
if ((launchpath + path.normalize('/elxr')) === thisscriptdir) {
// We ran unbuilt from the proper root with elxr subfolder.
console.log(`Instance Path : ${root}`)
}
else {
if (launchpath === thisscriptdir) {
// Same directory doesn't mean we are being run from elxr directory or the root directory.
// It could be a standalone elxr build which may or maynot be in the proper location.
if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
// Unbuilt therefore we are in the elxr directory.
root = path.normalize(launchpath + '/..');
}
else {
// Built version.
// check if we have a elxr subfolder.
if (fs.existsSync(launchpath + '/..' + path.normalize('/elxr'))) {
// Probably in the right place.
root = path.normalize(launchpath + '/..');
}
else {
// Assume launchpath is meaningless.
// Figure it out from the input instance name and environment parameters if we are in the right location.
root = path.normalize(launchpath + '/' + processedArgs._[1] + '/' + processedArgs.node_env)
}
}
}
}
instanceroot = root.replace(/\\/, '/');
__default.root = root;
return Promise.resolve(__default);
}
var launchpath = path.normalize(process.cwd())
var thisscriptdir = path.normalize(__dirname); // PB : TODO -- Thisscriptdir could be dislocated when run as a standalone file... We need to detect this where and how we were run.
// The easisest would be to ask for a target directory and default to current dir....
var instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;


//
var __default = { var __default = {


// Default is public server only. // Default is public server only.
// All public repos are by default available. // All public repos are by default available.
reposervers: ['https://git.bbh.org.in'] reposervers: ['https://git.bbh.org.in']
, repos: [ , repos: [
'setup'
, 'elxr'
, 'loopback-connector-mysql'
, 'loopback-jsonapi-model-serializer'
, 'loopback-component-jsonapi'
, 'ember-service-worker'
, 'ember-service-worker-asset-cache'
, 'ember-service-worker-cache-fallback'
, 'ember-service-worker-index'
, 'ember-sw-client-route'
{ repo : 'setup' }
, { repo : 'elxr' }
, { repo : 'loopback-connector-mysql' }
, { repo : 'loopback-jsonapi-model-serializer' }
, { repo : 'loopback-component-jsonapi' }
, { repo : 'ember-service-worker' }
, { repo : 'ember-service-worker-asset-cache' }
, { repo : 'ember-service-worker-cache-fallback' }
, { repo : 'ember-service-worker-index' }
, { repo : 'ember-sw-client-route' }
] ]


, elevated: [] , elevated: []
, node_env: 'development' , node_env: 'development'
} }


var __interactve_promts = {
get reposerver(){
return cli.prompt(this.reposervers, 'git default repo').then(reposerver => {
Object.defineProperty(this, 'reposerver', {
value: reposerver,
writable: false,
configurable : true,
enumerable : true
});
return reposerver
})
var hasElxr = function(path, options, cb) {
// PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
options = options || {};

var tasks = [
'/elxr' // Is there a subfolder named elxr
, '/elxr/.git' // which is self git repository
, '/elxr/.elxr' // and has .elxr subfolder
, '/elxr/.elxr/' + __ALIAS__STAMP__ // Which has our stamp.
]

if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
var value = existsFolderSync(path + tpath);
return { value, done : acc && !value };
}).value }

if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
var value = existsFolderSync(path + tpath);
return { value, done : acc && !value };
}).value );
return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
var value = existsFolderSync(path + tpath);
return { value, done : acc && !value };
}).value);
}

var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); }

var detectfromroot = function(root){
return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(root) ) }
}
var detectinstances = function () {
console.log(`launchpath = ${launchpath}`)
console.log(`thisscriptdir = ${thisscriptdir}`)

// PB : TODO -- !Postpone this.
console.log(`instanceroot = ${instanceroot}`) // Not yet confirmed...

// Note : Paths should already be normalized fefore this.

var root = instanceroot;
var detected = { root };
var instanceoptions = [clioverrides]

return hasElxr(launchpath).then( (elxrCliExists) => {

// We need a reference to the root director for elxr cli to be properly oriented.
if (( elxrCliExists && path.normalize(launchpath + '/elxr')) === thisscriptdir) {
// We were run from the proper root with elxr cli in the subfolder.
instanceroot = root = launchpath;
instanceoptions.splice( 0, 0, detected = { root })
instanceoptions.splice( 0, 0, detectfromroot(root))
}
else {
if(path.normalize(launchpath + '/elxr') === thisscriptdir) {
// elxrCliExists is false -- and yet thiscriptdir is still proper.
// PB : TODO -- Maybe a warning / abort if for some reason this scriptdir should not be taken over...
console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.')
instanceroot = root = launchpath;
instanceoptions.splice( 0, 0, detected = { root })
instanceoptions.splice( 0, 0, detectfromroot(root))
}
else if (launchpath === thisscriptdir) {
var parentHasElxr = hasElxrSync(launchpath + '/..')
// PB : TODO -- verify if we have .elxr folder in the parent...
if(!parentHasElxr) {
// ! thisscriptdir is not elxr.
console.error('Invalid run location in subfolder that looks like elxr. We should probably abort as elxr will not sync.')
}

// Same directory doesn't mean we are being run from elxr sub directory.
// In standalone build script we may or not be in the same location.
if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
// Unbuilt therefore we are in the elxr sub directory.

instanceroot = root = path.normalize(launchpath + '/..');
instanceoptions.splice( 0, 0, detected = { root });
instanceoptions.splice( 0, 0, detectfromroot(root));
}
else {
// Built version.
// We could have been run from the elxr subfolder. Highly likely that the built version isn't the full elxr.
if(parentHasElxr) {
// Built version was run from the full elxr subfolder. Should work
// PB : TODO -- but we should switch to the full version...
instanceroot = root = path.normalize(launchpath + '/..');
instanceoptions.splice( 0, 0, detected = { root })
instanceoptions.splice( 0, 0, detectfromroot(root))
}
else {
instanceroot = root = launchpath;
instanceoptions.splice( 0, 0, detected = { root })
instanceoptions.splice( 0, 0, detectfromroot(root))
// Assume current launchpath is a new instance and create.
// Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.

// if(clioverrides.instanceName) {
// if(clioverrides.node_env) {
// instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
// instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
// // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
// // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
// // eg : floder name can be elixir01 but instance name is elixr
// }
// else {
// instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + 'development')
// instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
// instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
// }
// }
// else {
// instanceroot = root = launchpath;
// if(clioverrides.node_env) {
// instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
// instanceoptions.splice( 0, 0, detectfromroot(root))
// }
// else {
// // Nothing was specified... We only have one option from root.
// instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
// }
// }
}
}
}
else {
if(elxrCliExists) {
instanceroot = root = launchpath;
instanceoptions.splice( 0, 0, detected = { root })
instanceoptions.splice( 0, 0, detectfromroot(root))
}
}
}
instanceroot = detected.root
__default.root = root;
clioverrides.root = clioverrides.root || root;
// Resolves empty array when No known instances detected.
return Promise.resolve(instanceoptions)
})

}

var getBoundEachPrompt = function(target, mustPrompt, promptables, choices) {
return function(prompts, 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.
// PB : TODO -- selectedinstance === __default check to prompt everything...
if( (mustPrompt[k] !== undefined && mustPrompt[k] !== null) && target[k] !== mustPrompt[k]
|| (mustPrompt[k] === undefined || mustPrompt[k] === null) && (target[k] === undefined || target[k] === null)
|| 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);
promptables[k].choices = choices[k]
Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
return await target[k]
})
}
delete mustPrompt[k]
return prompts
} }
, set reposerver(reposerver){
Object.defineProperty(this, 'reposerver', {
value: reposerver,
writable: false,
configurable : true,
enumerable : true
});
return reposerver
}

var __interactve_promts = function( target, choices ){

Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });

var interactionpoints = {
runchoice : {
label :
`Choose an option :
d) Install the default chess instance.
=> elxr i chess node_env=development --default
n) Create your custom new instance interactively
=> elxr i {{instanceName}} node_env={{environment}}
i) Choose an instance and environment to install
=> elxr i {{instanceName}} node_env={{environment}}
c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
=> elxr {{cmd}} {{instanceName}} node_env={{environment}}
h) Help
q) Quit
: `
, choices : []
, defaultchoice : 'c'
, interpret : function(choice){
var interpret_map = {
d : function(){
processedArgs._[0] = 'i'
target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
target.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
target.reposerver = 'https://git.bbh.org.in'
}
, n : function() { processedArgs._[0] = 'i' }
, i : function() { processedArgs._[0] = 'i' }
, c : async function() {
Object.defineProperty(this, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
label : `Enter cmd :
p) pull
Default <= p
: `
, defaultchoice : 'pull'
}
));

var cmd = await target['cmd'];
if (!cmd || cmd === 'p') { target['cmd'] = processedArgs._[0] = 'pull' }
else target['cmd'] = processedArgs._[0] = cmd
return cmd;
}
, h : function() { console.log(elxr.help()); process.exit() } // PB : TODO -- Why do we need log.
, q : function() { process.exit() }
}
var __interpreter = interpret_map['c']
// if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
if(interpret_map[choice]) __interpreter = interpret_map[choice];
return __interpreter.call(target)
}
}
, instanceName : { label : `Enter Instance Name ( <= ${target.instanceName || 'chess'} ) : `, choices : [], defaultchoice : 'chess'}
, instanceType : { label : `Enter Instance Type ( <= ${target.instanceType || 'development'} ) : `, choices : [], defaultchoice : 'development'}
, reposerver : { label : `Enter Instance Name ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `, choices : [], defaultchoice : 'https://git.bbh.org.in'}
} }

var eachPrompt = getBoundEachPrompt( target, promptkeys, interactionpoints, choices)
return Object.keys(interactionpoints).reduce(eachPrompt, [])
} }



var downloadsdir = '../Downloads'; var downloadsdir = '../Downloads';
var prerequisites = [ var prerequisites = [
{ {
return Promise.all(downloadtasks).then(() => { return any(installtasks) }) return Promise.all(downloadtasks).then(() => { return any(installtasks) })
} }


var getPromptableAsyncPropDescriptor = function(propName, choices, defaultchoise){
var getPromptableAsyncPropDescriptor = function(propName, promptable){
return { return {
get (){ get (){
return cli.prompt( choices, propName, defaultchoise).then(propValue => {
Object.defineProperty(this, propName, {
value: propValue,
writable: false,
configurable : true,
enumerable : true
});
return propValue
return cli.prompt( promptable.choices, promptable.label, promptable.defaultchoice ).then(propValue => {
var asyncprop = Promise.resolve(propValue)
if(promptable.interpret){
asyncprop = promptable.interpret(propValue)
}

return asyncprop.then(
()=>{
Object.defineProperty(this, propName, {
value: propValue,
writable: true,
configurable : true,
enumerable : true
});
return propValue
}
)
}) })
} }
// , set (propValue){ // , set (propValue){
// Object.defineProperty(this, propName, { // Object.defineProperty(this, propName, {
// value: propValue, // value: propValue,
// writable: false,
// writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
// configurable : true, // configurable : true,
// enumerable : true // enumerable : true
// }) // })
} }
} }





function acquirelocalinstances(selected){
// utils.assign is used to cleanup duplicates...
var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
return chessinstances
}

function findlocalinstances(chessinstances, instanceoptions){
// We can expect a .elxr at each level.
['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../..' /* instanceNames */].
earlyreduce( ( value, p, i, a )=>{
var localinstancesPath = `${instanceroot}/${p}.elxr`;
if(existsSync( localinstancesPath )) {
try {
var chessinstances = acquirelocalinstances( { localinstancesPath } )
return Object.keys(chessinstances).earlyreduce( ( value, instanceName) => {
return Object.keys(chessinstances[instanceName]).earlyreduce( (value, instanceType) => {
if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize( instanceroot) ) {
instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType])
return {
value : chessinstances[instanceName][instanceType]
, done : true
};
}
})
})
}
catch(e){
return { }
}
}
else return { }
}
)
}


// function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) } // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
var selectedinstance = null; var selectedinstance = null;
var chessinstances = { current_run : {} }; var chessinstances = { current_run : {} };
var promptkeys = {
// Try not to prompt anything unless absolutely necessary or reconfirm is forced.
// 'instanceName' : true
// , 'node_env' : true
}

function createChessInsance( cfg ){
var inst = {};
var __new = Object.assign({}, __default, cfg)
inst[cfg.node_env] = __new; return inst;
}

acquireElevationState().then(() => { acquireElevationState().then(() => {
var skipprerequisites = false; var skipprerequisites = false;
var clioverrides = { }
function initinstances(selected) {
// PB : TODO -- processedArgs should already be part of selected.
var instanceName = processedArgs._[1] = processedArgs._[1] || chessinstances.current_run.instanceName || selected.instanceName;
var node_env = processedArgs.node_env = processedArgs.node_env || chessinstances.current_run.node_env || selected.node_env;
chessinstances[instanceName] = chessinstances[instanceName] || {}
chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || selected;
chessinstances['current_run'] = chessinstances[instanceName][selected.node_env] ?
{ instanceName: instanceName, node_env: node_env } : (chessinstances['current_run'] || { instanceName: instanceName, node_env: node_env })
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.


// chessinstances[chessinstances.current_run.instanceName] = chessinstances[chessinstances.current_run.instanceName] || {}
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
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(!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(!reposerver) {
promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
}

chessinstances[instanceName] = chessinstances[instanceName] || createChessInsance( {
instanceName, node_env, root : selected_overrides.root, reposerver : promptkeys['reposerver'] } );
chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root }


if(path.normalize(selected.root) !== path.normalize(chessinstances[instanceName][node_env].root)) {
throw "Mismatched chessinstances config found " + chessinstances[instanceName][node_env].root + ' does not match ' + selected.root
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. // Override sequence.
// __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
selectedinstance = Object.assign(
selected
, chessinstances[instanceName][node_env]
selectedinstance = utils.assign(
chessinstances[instanceName][node_env]
, clioverrides , clioverrides
, selected_overrides
// , __interactve_promts -- Cant just override. Also need selectedinstance to be ready... // , __interactve_promts -- Cant just override. Also need selectedinstance to be ready...
); );


chessinstances[instanceName] = chessinstances[instanceName] || {}
chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
// 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) { if(!selectedinstance.repos[0].repo) {
console.warn('repo manifest has obsolete format. Attempting upgrade.') console.warn('repo manifest has obsolete format. Attempting upgrade.')
selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } }) selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
// Config from server always override merges into selection except for the current selection. // Config from server always override merges into selection except for the current selection.
// PB : TODO -- utils.assign Array merges are non-distinct... // PB : TODO -- utils.assign Array merges are non-distinct...
chessinstances[instanceName][node_env] = selectedinstance = utils.assign(selected, selectedinstance)
chessinstances[instanceName][node_env] = selectedinstance;
// chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance; // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
cacheWriteInstanceConfig(chessinstances) cacheWriteInstanceConfig(chessinstances)
// PB : TODO -- We should probably write the new server config also... // PB : TODO -- We should probably write the new server config also...


return chessinstances return chessinstances
} }
function acquirelocalinstances(selected){
var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
return chessinstances
}


var noprerequisites = { var noprerequisites = {
add : true, 'set-url' : true, 'repo-relocate' : true add : true, 'set-url' : true, 'repo-relocate' : true
, remote : true , remote : true
return elxrworker() return elxrworker()
} }


return detectInstance().then((detectedInstance)=>{
var getchoices = function(detectedinstanceoptions, promptkeys){

var instances = []
var reposervers = [];
var instnaceNames = []
var instanceTypes = ['development', 'production'];
Object.keys( chessinstances).forEach(instanceName => {
if(instanceName === 'current_run') return;
Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
var instance = chessinstances[instanceName][node_env];
reposervers = reposervers.concat(instance.reposervers)
if(instance.reposerver) reposervers.push(instance.reposerver)
instances.push(instance)
instanceTypes.push(instance.node_env)
instnaceNames.push(instance.instanceName)
})
})
instances = instances.concat(detectedinstanceoptions)


processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
processedArgs.node_env ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env
: (process.env.NODE_ENV && process.env.NODE_ENV.trim()) ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()): null;
if(promptkeys['instanceName']) instnaceNames.push(selectedinstance['instanceName'])
if(promptkeys['instanceName']) instnaceNames.push(promptkeys['instanceName'])
if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers'])
clioverrides.reconfirm = processedArgs.reconfirm
var choices = {
'instanceName' : Array.from( new Set(instnaceNames) )
, 'reposerver' : Array.from( new Set(reposervers) )
, 'instanceType' : Array.from( new Set(instanceTypes) )
}

return choices;
}

return detectinstances().then((detectedinstanceoptions)=>{
detectedinstanceoptions.splice(0,0, __default)
selectedinstance = Object.assign(detectedInstance, clioverrides);
var todo = Promise.resolve(true);
var promptkeys = { 'instanceName' : processedArgs._[1] }


// PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
selectedinstance = utils.assign( ...detectedinstanceoptions.slice(-2) )
promptkeys = utils.assign(promptkeys, clioverrides)
if(clioverrides.reconfirm) { if(clioverrides.reconfirm) {
var reconfirm = {
'instanceName' : selectedinstance['instanceName'] === 'chess'
}
}
else {
var reconfirm = {};
}
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]
var reconfirm = { 'instanceName' : selectedinstance['instanceName'] === 'chess' }
} }
else { var reconfirm = {}; }
try { try {
chessinstances = acquirelocalinstances(selectedinstance);
initinstances(selectedinstance)
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 })
chessinstances = acquirelocalinstances(selectedinstance);
findlocalinstances(chessinstances, detectedinstanceoptions)
var choices = getchoices(detectedinstanceoptions, promptkeys)
var todo = any( __interactve_promts(selectedinstance, choices) ).then(()=>{
return initinstances(selectedinstance)
})
} }
catch (e) { catch (e) {
console.error(e) // Missing chessinstances is not an error...
initinstances(selectedinstance)
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 })
// PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
var choices = getchoices(detectedinstanceoptions, promptkeys)
var todo = any( __interactve_promts(selectedinstance, choices) ).then(()=>{
return initinstances(selectedinstance)
})

if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){ if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
// Weve been told what to do.
// Weve not been told what to do.
todo = todo.then(() => { return acquireChoices(selectedinstance) }) todo = todo.then(() => { return acquireChoices(selectedinstance) })
} }
todo = todo.then(() => { todo = todo.then(() => {
try { try {
chessinstances = acquirelocalinstances(selectedinstance) chessinstances = acquirelocalinstances(selectedinstance)
findlocalinstances(chessinstances, detectedinstanceoptions)
detectedinstanceoptions.splice(0,0, __default)
initinstances(selectedinstance) initinstances(selectedinstance)
} }
catch (e) { catch (e) {
.then(()=>{ .then(()=>{


if(!__isElevated) { if(!__isElevated) {
ensureDirectoryExistence(`${selectedinstance.root}/.elxr/readme.txt`)
ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`)
// collect garbage // collect garbage
return dirs( (dir)=>{ return dirs( (dir)=>{
var matches = /run-(.*)/gm.exec(dir.name) var matches = /run-(.*)/gm.exec(dir.name)

+ 0
- 4
rollup.config.js View File

// exclude : [ 'chessinstances.js' ] // exclude : [ 'chessinstances.js' ]
}), nodeResolve(), versionInjector()] }), nodeResolve(), versionInjector()]
}; };

// Dr Kamat
// Rahul Roji
// 06259

Loading…
Cancel
Save