Browse Source

Added local createInstance

production
guest 3 years ago
parent
commit
4f69189513
1 changed files with 193 additions and 58 deletions
  1. 193
    58
      index.js

+ 193
- 58
index.js View File

}()); }());


const { existsSync } = require('fs'); const { existsSync } = require('fs');
const existslink = function(name, cb){
fs.lstat(name, (error, stats) => {
if (error) {
console.log(error);
cb(error)
}
else {
console.log("Stats object for: example_directory.txt");
console.log(stats);
// Using methods of the Stats object
console.log("Path is file:", stats.isFile());
console.log("Path is directory:", stats.isDirectory());
cb(null, true)
}
});
}
const existsFolderSync = existsSync; const existsFolderSync = existsSync;
const fs = require('fs') const fs = require('fs')


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', selectedinstance.username].join(' ')}`
, title: `'git', ${['config', '--replace-all', 'core.symlinks', selectedinstance.username].join(' ')}`
}) })
.then(() => { .then(() => {
if (__isElevated) { if (__isElevated) {


var tasks = [ var tasks = [
() => { () => {
if (existsSync('config')) {
var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
return p;
}
else return Promise.resolve(true);
var promise = new Promise((resolve, reject)=>{
existslink('config', function(err, data){
if(data) {
var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
return resolve(p);
}
else resolve(false)
})
})
return promise;
}, },
() => { () => {
if (existsSync('data')) {
var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
return p;
}
else return Promise.resolve(true);
var promise = new Promise((resolve, reject)=>{
existslink('data', function(err, data){
if(data) {
var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
return resolve(p);
}
else resolve(false)
})
})
return promise;
}, },
]; ];
runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development'; runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
process.exit() process.exit()
} }


// PB : TODO -- accept additional arg - an array specifying custom configPriority.
var acquireConfig = function(slections){ var acquireConfig = function(slections){
var configPriority = [ 'clusterNodeInstance', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ] 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).then(()=>{
return acquireData(slections)
})
}

var instanceData = (function(){
return {
clusterNodeInstance(selected) { var clusternodename = 'node01'
return __acquireData(selected, selected.username, clusternodename
, selected.instanceName + '-config-' + selected.node_env + `-${clusternodename}`
, function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
return e; }
)
}
, ownerInstnace(selected) { return __acquireData(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.');
return e }
)
}
// PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
, commonInstance(selected) { return __acquireData(selected, defaultRepoOwner
// , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
) }
, genericChessInstance(selected) { return __acquireData(selected) }
}
})()

var acquireData = function(slections){
var configPriority = [ 'clusterNodeInstance', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
return any(configPriority.map(cfg => { return function() { return instanceData[cfg](slections) } } ), true, true)
} }


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


var __acquireData = function (selected, owner, clusternodename, datarepo, errHandler) {

datarepo = datarepo || selected.instanceName + '-config-' + selected.node_env;

var errorHandler = (e) => {
if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${owner}/${datarepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
// console.error('Could not connect to repo server. Timed Out')
return cli.prompt( ['(y)es', '(n)o', '(r)etry'], 'Could not connect to repo server. Timed Out. Would you like to switch server ? (y/n) ', 'y' ).then(propValue => {
if(propValue === 'y') {
reconfirm = getReconfirmAll()
return startElxr()
}
else if(propValue === 'r'){
return acquireConfig(selected)
}
else process.exit()
})
}

if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${owner}/${datarepo}.git/' not found`))){
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
, 'Data repo for instance not found. Would you like to ', 'e' ).then(propValue => {
if(propValue === 't') {
selectedinstance.local = true; return createInstanceData(selectedinstance)
}
if(propValue === 'i') return eNotImplemented()
if(propValue === 'f') return eNotImplemented()
if(propValue === 'o') return eNotImplemented()
if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
// if(propValue === 'o') createChessInstance(selectedinstance, orgname)
else process.exit()
})
}
console.warn(e)
throw e; //('Config acquisition failed.')
}

var successHandler = () => {

}

return performPull(datarepo, 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())
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. 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.... // The easisest would be to ask for a target directory and default to current dir....
// User can always add more branches and remotes as needed. Mainifest only occupies // User can always add more branches and remotes as needed. Mainifest only occupies
// well defined namespaces // well defined namespaces
var remotes = { var remotes = {
// these are both fetch and push remotes. Use push - remotes to override push.
'chess' : { path : `/chess/`, push : 'no-pushing' }
// these are both fetch and push remotes. Use push - remotes to override push.
'chess' : {
server : `${options.reposerver}`, user : 'chess', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
, push : 'no-pushing' }
, 'baptistdev-public' : {
server : `https://github.com`, user : 'baptistdev', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
, push : 'no-pushing' }

// Multiple urls dont tell us the current origin which may be // Multiple urls dont tell us the current origin which may be
// different based on currently available/accessible based on device and client. // different based on currently available/accessible based on device and client.
// We just treat them as different remotes and merge as needed. // We just treat them as different remotes and merge as needed.
// //
, 'origin' : { path : `/${options.username}/` }
, 'origin-public' : { path : `/${options.username}/` }
, 'origin-unc' : { path : `/${options.username}/` }
, 'origin' : {
server : `${options.reposerver}`, user : '${options.username}', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
}
, 'origin-public' : {
server : `https://git.bbh.org.in`, user : 'chess', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
, push : {
server : `${options.reposerver}`, user : `${options.username}`, path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`}
}
}
, 'origin-unc' : {
server : `//172.16.0.27/repos`, user : '${options.username}', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
}
// , { `${options.username}` : `https://git.bbh.org.in/${options.username}/elxr.git` } // , { `${options.username}` : `https://git.bbh.org.in/${options.username}/elxr.git` }
} }


, 'https://git.bbh.org.in' : { users, remotes, external : true } , 'https://git.bbh.org.in' : { users, remotes, external : true }
, '//172.16.0.27/repos' : { users, remotes } , '//172.16.0.27/repos' : { users, remotes }
, 'https://github.com' : { , 'https://github.com' : {
// We host a miniaml set of repositories in github.
get users() { return [{ username : `${this.username}` }]}, username : `baptistdev`
, remotes : { get 'baptistdev-public'() { return {path : `/${this.username}/`, push : 'no-pushing'} }
// , Add other remotes here.
}
, external : true, public : true
// We host a miniaml set of repositories in github.
get users() { return [{ username : `${this.username}` }]}, username : `baptistdev`
, remotes : {
'baptistdev-public' : {
server : `https://github.com`, user : 'baptistdev', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
, push : 'no-pushing' }
// , Add other remotes here.
}
, external : true, public : true
} }
} }
return { return {
reposervers : Object.keys(reposerverinstances)
, reposerverinstances
reposervers : Object.keys(reposerverinstances)
, reposerverinstances


// Common baseline repos for all chess instances.
, repos : [
{ repo : 'ember-masonry-grid' /*, branch : master*/ } // Default need not be specified.
// Common baseline repos for all chess instances.
, repos : [
{ repo : 'ember-masonry-grid' /*, branch : master*/ } // Default need not be specified.
, { repo : 'bbhverse' } , { repo : 'bbhverse' }
, { repo : 'clientverse' } , { repo : 'clientverse' }
, { repo : 'serververse' } , { repo : 'serververse' }
, { repo : 'global-this' } , { repo : 'global-this' }
] ]


// PB : TODO -- lighter defaults for lite new instance creation..
, repos: [
{ 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 : [ ]
, exludeMergeRepos : { } , exludeMergeRepos : { }
} }
, choices : choices['instanceType'], defaultchoice : 'development'} , choices : choices['instanceType'], defaultchoice : 'development'}
, reposerver : { label : `Enter Repo Url ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : ` , reposerver : { label : `Enter Repo Url ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `
, choices : choices['reposerver'], defaultchoice : 'https://git.bbh.org.in'} , choices : choices['reposerver'], defaultchoice : 'https://git.bbh.org.in'}
, username : { label : `Enter User Id for ${target.reposerver} ( <= ${target.username || 'chess'} ) : `
, choices : choices['username'], defaultchoice : 'chess'}
, password : { label : `Enter Password for ${target.username} @ ${target.reposerver} ( <= ${target.password || ''} ) : `
, choices : choices['password'], defaultchoice : '***'}
, email : { label : `Enter Email for ${target.username} @ ${target.reposerver} ( <= ${target.email || ''} ) : `
, choices : choices['email'], defaultchoice : 'guest@bbh.org.in'}
, get username() { return { label : `Enter User Id for ${target.reposerver} ( <= ${target.username || 'chess'} ) : `
, choices : choices['username'], defaultchoice : 'chess'} }
, get password() { return { label : `Enter Password for ${target.username} @ ${target.reposerver} ( <= ${target.password || ''} ) : `
, choices : choices['password'], defaultchoice : '***'} }
, get email() { return { label : `Enter Email for ${target.username} @ ${target.reposerver} ( <= ${target.email || ''} ) : `
, choices : choices['email'], defaultchoice : 'guest@bbh.org.in'} }

} }


var shell = new ActiveXObject('shell.application'); var shell = new ActiveXObject('shell.application');
// alert('launching node privilged. ' + processedArgs['nodepath']) // alert('launching node privilged. ' + processedArgs['nodepath'])
// shell.ShellExecute('where', 'node', '', '', 10); // shell.ShellExecute('where', 'node', '', '', 10);
// shell.ShellExecute('cmd.exe', '/k notepad.exe', '', 'runas', 1);
// shell.ShellExecute('cmd.exe ', '/k node "' + cargs + '"', '', 'runas', 1);
shell.ShellExecute('node', cargs, '', 'runas', 1); shell.ShellExecute('node', cargs, '', 'runas', 1);
// shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1); // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
var fso = new ActiveXObject('Scripting.FileSystemObject'); var fso = new ActiveXObject('Scripting.FileSystemObject');
} }


const https = require('https') const https = require('https')
const http = require('http')
const http = require('http');
const { resolve } = require('path');
const RESTAPI = (function(){ const RESTAPI = (function(){


// Singleton // Singleton
, cwd : instanceroot , cwd : instanceroot
, runas: processedArgs.runas , runas: processedArgs.runas
} }
cmdseq = ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]

return any(cmdseq.map(getshelltask)).then(() => {
return true
})
var cmdseq = [
['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
]
return any(cmdseq.map(getshelltask)).then(() => { return true })
} }
else { else {
// http://try.gitea.io/api/v1/org/{org}/repos // http://try.gitea.io/api/v1/org/{org}/repos
if(!__isElevated) { if(!__isElevated) {
} }
else { else {
specifictask = ()=>{ Promise.resolve(true) }
specifictask = ()=>{ return Promise.resolve(true) }
} }
inittasks.push( specifictask().catch((err) => { inittasks.push( specifictask().catch((err) => {

Loading…
Cancel
Save