Browse Source

elxr can now be built into a single standalone file

master
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

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




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

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


// PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
console.dir(processedArgs) console.dir(processedArgs)
var globSync = require('glob').sync; var globSync = require('glob').sync;


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


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)=>{
return ()=>{ 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;
} }
} }


// var pullCmd = ['pullall', [], { cwd : repo }] // var pullCmd = ['pullall', [], { cwd : repo }]
if(useGitPull) pullCmd = ['git', ['pull'], { if(useGitPull) pullCmd = ['git', ['pull'], {
inherit : true, shell: true, inherit : true, shell: true,
cwd : repo
cwd : instanceroot + '/' + repo
// , env: process.env // , env: process.env
, runas : processedArgs.runas , runas : processedArgs.runas
, title : `git pull ${repo}` , title : `git pull ${repo}`
} }


var performPull = (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(()=>{ return nodeShellExec.apply(null, getPullCmd(repo)).then(()=>{
if(__isElevated) { if(__isElevated) {
fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success:true}), {'flag':'a+'} ) fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success:true}), {'flag':'a+'} )
var tasks = [] var tasks = []
tasks.push(op['pull']); tasks.push(op['pull']);
tasks.push( getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures : true} ] ) )
tasks.push(op['use'])
if(!__isElevated){ if(!__isElevated){
tasks.push( getShellTask.apply(null, ['rm', ['run.js']] ) )
tasks.push(op['use'])
tasks.push(op['npmi']) tasks.push(op['npmi'])
} }


5) Iterates all repos and merge from source configured in mergeSource. 'git', ['merge', mergeSource], 5) Iterates all repos and merge from source configured in mergeSource. 'git', ['merge', mergeSource],
*/ */
var runconfig = { NODE_ENV : repomanifest.node_env } 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') && if((!processedArgs.runas || processedArgs.runas !== 'self') &&
runconfig.NODE_ENV && runconfig.NODE_ENV === (repomanifest.node_env || runconfig.NODE_ENV) && runconfig.NODE_ENV && runconfig.NODE_ENV === (repomanifest.node_env || runconfig.NODE_ENV) &&
repomanifest.instanceName && runconfig.use === repomanifest.instanceName) { repomanifest.instanceName && runconfig.use === repomanifest.instanceName) {
if(processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1]; if(processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
if(!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' } if(!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
// console.log(process.env.cwd) // 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. // cant use git checkout -b it fails with branch already exists.
var performCheckout = (repo, branch)=>{ var performCheckout = (repo, branch)=>{
// The main elxr cli process // The main elxr cli process
function elxrworker(hasconfig){ 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(()=>{ return acquireElevationState().then(()=>{
// Everything runs after this check is completed. Elevation occurs out of process when needed. // Everything runs after this check is completed. Elevation occurs out of process when needed.
gitRepos = repomanifest.repos gitRepos = repomanifest.repos
processedArgs._[0] = 'i' processedArgs._[0] = 'i'
processedArgs._[1] = processedArgs._[1] || 'chess' processedArgs._[1] = processedArgs._[1] || 'chess'
processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development' 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' else if(choice === 'h'){ processedArgs._[0] = 'h'
fs.writeFileSync('run.done', 'noop help'); fs.writeFileSync('run.done', 'noop help');
processedArgs._[0] = 'i' processedArgs._[0] = 'i'
processedArgs._[1] = instanceName ? instanceName : 'elixir' processedArgs._[1] = instanceName ? instanceName : 'elixir'
return p1.ask(`Enter Environment ( <= development ) : `).then(function(node_env){ return p1.ask(`Enter Environment ( <= development ) : `).then(function(node_env){
p1.close()
processedArgs.node_env = node_env ? node_env : 'development' processedArgs.node_env = node_env ? node_env : 'development'
if(choice === 'n') { if(choice === 'n') {
defaultRepoServer = 'https://git.bbh.org.in'
console.warn( console.warn(
chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess')) chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
process.exit(); 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'){ } else if(choice === 'c'){
processedArgs._[0] = 'pull' processedArgs._[0] = 'pull'
} }
else processedArgs._[0] = cmd 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()
})
}) })
}) })
}) })
} }


var acquireConfig = function(){ var acquireConfig = function(){
var instance = getInstance();
var configrepo = processedArgs._[1]+'-config-'+processedArgs.node_env; var configrepo = processedArgs._[1]+'-config-'+processedArgs.node_env;
return performPull(configrepo).then(()=>{ 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)() repomanifest = require(manifestpath)()
var chessinstances = {} var chessinstances = {}
try { try {
chessinstances = require('../chessinstances.js');
chessinstances = require(path.normalize(instance.root + '/chessinstances.js'));
chessinstances[processedArgs._[1]][processedArgs.node_env] = repomanifest; chessinstances[processedArgs._[1]][processedArgs.node_env] = repomanifest;
} }
catch(e) { catch(e) {
chessinstances[processedArgs._[1]][processedArgs.node_env] = repomanifest; chessinstances[processedArgs._[1]][processedArgs.node_env] = repomanifest;
} }
chessinstances['current_run'] = { instanceName : processedArgs._[1], node_env : processedArgs.node_env } 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.') 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 { 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._[1] = chessinstances.current_run.instanceName;
processedArgs.node_env = chessinstances.current_run.node_env; processedArgs.node_env = chessinstances.current_run.node_env;
repomanifest = chessinstances[chessinstances.current_run.instanceName][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)=>{ return acquireConfig().catch((e)=>{
console.error('Exisitng config Failed. Fix config and rerun or chose another.') console.error('Exisitng config Failed. Fix config and rerun or chose another.')
console.error(e); console.error(e);
}).then(()=>{ return elxrworker(true) }) }).then(()=>{ return elxrworker(true) })
} }
catch(e) { catch(e) {
console.error(e)
return acquireChoices().then(()=>{ return acquireChoices().then(()=>{
return acquireConfig().catch((e)=>{ return acquireConfig().catch((e)=>{
console.error('Chosen cofiguraton failed or not found') console.error('Chosen cofiguraton failed or not found')

+ 11
- 3
package.json View File

"description": "", "description": "",
"main": "index.js", "main": "index.js",
"scripts": { "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": [], "keywords": [],
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"tree-kill": "^1.2.2",
"bbhverse": "file:../bbhverse",
"chalk": "^4.1.0",
"glob": "^7.1.2", "glob": "^7.1.2",
"bbhverse": "file:../bbhverse"
"tree-kill": "^1.2.2"
}, },
"bin": { "bin": {
"elxr": "bin/elxr" "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

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