Browse Source

elxr can now be built into a single standalone file

pull/4/head
demo 3 years ago
parent
commit
2613d0b385
3 changed files with 130 additions and 29 deletions
  1. 92
    26
      index.js
  2. 11
    3
      package.json
  3. 27
    0
      rollup.config.js

+ 92
- 26
index.js View File

@@ -10,6 +10,10 @@ var nodeShellExec = cli.nodeShellExec;
var chalk = require('chalk')


const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
function getVersion() { return BUILD_VERSION; }
console.log(getVersion())

// 'use strict';

// PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
@@ -30,17 +34,22 @@ const processedArgs = cliargs(process.argv.slice(2));
console.dir(processedArgs)
var globSync = require('glob').sync;

var path = require('path');
const { isMaster } = require('cluster');

var ENV = Object.assign({}, process.env); // Shallow clone it.

var getShellTask = (command, args, options)=>{
return ()=>{
nodeShellExec.apply(null, [command, args, Object.assign({
inherit : true, shell: true, env : ENV, title : `${command} ${args}`
}, options)
])
var p = nodeShellExec.apply(null, [command, args, Object.assign({
inherit : true, shell: true, env : ENV, title : `${command} ${args}`
}, options)
])
if(options.ignorefailures){
return p.catch(e=>{
// Ignore. Not a major error.
})
}
else return p;
}
}

@@ -53,7 +62,7 @@ var getPullCmd = (repo)=>{
// var pullCmd = ['pullall', [], { cwd : repo }]
if(useGitPull) pullCmd = ['git', ['pull'], {
inherit : true, shell: true,
cwd : repo
cwd : instanceroot + '/' + repo
// , env: process.env
, runas : processedArgs.runas
, title : `git pull ${repo}`
@@ -62,8 +71,8 @@ var getPullCmd = (repo)=>{
}

var performPull = (repo) => {
if(existsSync(repo)) {
console.log('pulling ' + repo)
if(existsSync(instanceroot + '/' + repo)) {
console.log('pulling ' + instanceroot + '/' + repo)
return nodeShellExec.apply(null, getPullCmd(repo)).then(()=>{
if(__isElevated) {
fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success:true}), {'flag':'a+'} )
@@ -672,9 +681,9 @@ var op = {
var tasks = []
tasks.push(op['pull']);
tasks.push( getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures : true} ] ) )
tasks.push(op['use'])
if(!__isElevated){
tasks.push( getShellTask.apply(null, ['rm', ['run.js']] ) )
tasks.push(op['use'])
tasks.push(op['npmi'])
}

@@ -867,7 +876,7 @@ var op = {
5) Iterates all repos and merge from source configured in mergeSource. 'git', ['merge', mergeSource],
*/
var runconfig = { NODE_ENV : repomanifest.node_env }
try { runconfig = Object.assign(runconfig, require('../run.js')) } catch(e) { }
try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch(e) { }
if((!processedArgs.runas || processedArgs.runas !== 'self') &&
runconfig.NODE_ENV && runconfig.NODE_ENV === (repomanifest.node_env || runconfig.NODE_ENV) &&
repomanifest.instanceName && runconfig.use === repomanifest.instanceName) {
@@ -899,11 +908,10 @@ var op = {
if(processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
if(!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
// console.log(process.env.cwd)
fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
var checkoutMap = {
'development' : 'master',
}
// Maps an environment to a branch. Not required if the branch is appropriately named.
var checkoutMap = { 'development' : 'master'}

// cant use git checkout -b it fails with branch already exists.
var performCheckout = (repo, branch)=>{
@@ -1197,9 +1205,6 @@ var elxr = {
// The main elxr cli process
function elxrworker(hasconfig){
defaultRepoServer = repomanifest.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
ENV.NODE_ENV = repomanifest.node_env;

return acquireElevationState().then(()=>{
// Everything runs after this check is completed. Elevation occurs out of process when needed.
gitRepos = repomanifest.repos
@@ -1301,7 +1306,9 @@ We will run your choice of default or create your own at the next prompt.
processedArgs._[0] = 'i'
processedArgs._[1] = processedArgs._[1] || 'chess'
processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
getManifest()
defaultRepoServer = 'https://git.bbh.org.in'
getManifest() // PB : TODO -- acquire the manifest directly from http url instead of clone before cloning the config. Since
// This is because the manifest at any server location can redirect to the preferred server..
}
else if(choice === 'h'){ processedArgs._[0] = 'h'
fs.writeFileSync('run.done', 'noop help');
@@ -1313,13 +1320,19 @@ We will run your choice of default or create your own at the next prompt.
processedArgs._[0] = 'i'
processedArgs._[1] = instanceName ? instanceName : 'elixir'
return p1.ask(`Enter Environment ( <= development ) : `).then(function(node_env){
p1.close()
processedArgs.node_env = node_env ? node_env : 'development'
if(choice === 'n') {
defaultRepoServer = 'https://git.bbh.org.in'
console.warn(
chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
process.exit();
}
return p1.ask(`Enter preferred repo server ( <= https://git.bbh.org.in ) : `).then(function(reposerver){
p1.close()
if(!reposerver) defaultRepoServer = 'https://git.bbh.org.in'
})

})
})
} else if(choice === 'c'){
@@ -1336,7 +1349,10 @@ We will run your choice of default or create your own at the next prompt.
processedArgs._[0] = 'pull'
}
else processedArgs._[0] = cmd
p1.close()
return p1.ask(`Enter preferred repo server ( <= https://git.bbh.org.in ) : `).then(function(reposerver){
if(!reposerver) defaultRepoServer = 'https://git.bbh.org.in'
p1.close()
})
})
})
})
@@ -1350,13 +1366,15 @@ We will run your choice of default or create your own at the next prompt.
}

var acquireConfig = function(){
var instance = getInstance();
var configrepo = processedArgs._[1]+'-config-'+processedArgs.node_env;
return performPull(configrepo).then(()=>{
var manifestpath = '../'+processedArgs._[1]+'-config-'+processedArgs.node_env+'/repo-manifest';
var manifestpath = path.normalize(instance.root + '/' +processedArgs._[1]+'-config-'+processedArgs.node_env+'/repo-manifest');
repomanifest = require(manifestpath)()
var chessinstances = {}
try {
chessinstances = require('../chessinstances.js');
chessinstances = require(path.normalize(instance.root + '/chessinstances.js'));
chessinstances[processedArgs._[1]][processedArgs.node_env] = repomanifest;
}
catch(e) {
@@ -1364,24 +1382,72 @@ var acquireConfig = function(){
chessinstances[processedArgs._[1]][processedArgs.node_env] = repomanifest;
}
chessinstances['current_run'] = { instanceName : processedArgs._[1], node_env : processedArgs.node_env }
fs.writeFileSync('chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances) + '', {'flag':'w'} )
fs.writeFileSync( instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances) + '', {'flag':'w'} )
defaultRepoServer = repomanifest.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
ENV.NODE_ENV = repomanifest.node_env;
})
.catch(()=>{
.catch((e)=>{
console.error(e)
console.error('Config acquisition failed.')
})
}

var launchpath = process.cwd()
var thisscriptdir = __dirname
var instanceroot = launchpath;
var getInstance = 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;
return { root };
}

try {
var chessinstances = require('../chessinstances.js');
var detectedInstance = getInstance(); // From launch location etc.

var chessinstances = require(path.normalize(detectedInstance.root + '/chessinstances.js'));
processedArgs._[1] = chessinstances.current_run.instanceName;
processedArgs.node_env = chessinstances.current_run.node_env;
repomanifest = chessinstances[chessinstances.current_run.instanceName][chessinstances.current_run.node_env]
// defaultRepoServer = repomanifest.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available...
return acquireConfig().catch((e)=>{
console.error('Exisitng config Failed. Fix config and rerun or chose another.')
console.error(e);
}).then(()=>{ return elxrworker(true) })
}
catch(e) {
console.error(e)
return acquireChoices().then(()=>{
return acquireConfig().catch((e)=>{
console.error('Chosen cofiguraton failed or not found')

+ 11
- 3
package.json View File

@@ -4,17 +4,25 @@
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "echo \"Error: no test specified\" && exit 1",
"build-commented": "rollup index.js --format cjs --file elxr.js",
"build": "rollup -c"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"tree-kill": "^1.2.2",
"bbhverse": "file:../bbhverse",
"chalk": "^4.1.0",
"glob": "^7.1.2",
"bbhverse": "file:../bbhverse"
"tree-kill": "^1.2.2"
},
"bin": {
"elxr": "bin/elxr"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^17.1.0",
"@rollup/plugin-node-resolve": "^11.2.0",
"rollup-plugin-version-injector": "^1.3.2"
}
}

+ 27
- 0
rollup.config.js View File

@@ -0,0 +1,27 @@
import commonjs from '@rollup/plugin-commonjs';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import versionInjector from 'rollup-plugin-version-injector';

export default {
input: 'index.js',
output: {
file : 'elxr.js'
, format: 'cjs'
},
// external: ['chessinstances'],
// globals: { chessinstances : chessinstances},
// external : [ 'chessinstances.js' ],
// exclude : [ 'chessinstances.js' ],
plugins: [commonjs({
dynamicRequireTargets: [
// include using a glob pattern (either a string or an array of strings)
'**/cu*.js'
]
// ,
// exclude : [ 'chessinstances.js' ]
}), nodeResolve(), versionInjector()]
};

// Dr Kamat
// Rahul Roji
// 06259

Loading…
Cancel
Save