Aksha Thomas 3 anni fa
parent
commit
21560c74ec
10 ha cambiato i file con 4658 aggiunte e 18502 eliminazioni
  1. 3
    1
      bin/elxr
  2. 16
    7
      cliverse.js
  3. 1720
    16585
      elxr.js
  4. 1983
    1540
      i.js
  5. 170
    63
      i.win.js
  6. 718
    227
      index.js
  7. 2
    2
      package.json
  8. 46
    0
      repo-manifest.js
  9. 0
    4
      rollup.config.js
  10. 0
    73
      windowselevate.hta

+ 3
- 1
bin/elxr Vedi File

@@ -3,9 +3,11 @@
var ENV = Object.assign({}, process.env); // Shallow clone it.

const spawn = require('child_process').spawn;
console.dir(process.argv.slice(2))

const child = spawn(
(process.platform === 'win32' ? 'npm.cmd' : 'npm')
, ['run', 'index'].concat(process.argv.slice(2)), { cwd: __dirname });
, ['run', 'index', '--'].concat(process.argv.slice(2)), { cwd: __dirname });

// const child = spawn(
// 'C:\\Program Files\\Git\\bin\\sh.exe'

+ 16
- 7
cliverse.js Vedi File

@@ -56,13 +56,15 @@ function nodeShellExec() {
});
}
child.on('close', (code) => {
console.log('Proper close was fired')
// console.log('Proper close was fired')
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 = { messages, result: `${opts.title} exited with code ${code}`, success, code }
if(opts.evaluateResult) logEntry = opts.evaluateResult(false, logEntry);
};
if(opts.stdio !== 'ignore') {
logEntry = { result: `${opts.title} exited with code ${code}`, messages, code }
logEntry.success = success;
if(opts.evaluateResult) logEntry = opts.evaluateResult(success, logEntry);
if(opts.runas){
// success ? logEntry.success = true : null;
fs.writeFileSync('run.log', ', ' + JSON.stringify(logEntry), {'flag':'a+'} )
@@ -88,9 +90,11 @@ function nodeShellExec() {
}

var prompt = function(choices, label, defaultchoice){
var choices = choices || [];
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 => {
// propName = promptable.interpret(propValue)
if(!choice) return defaultchoice || choices[0];
if(choice && isNaN(+choice)) return choice;
return choices[(+choice) - 1];
@@ -107,9 +111,14 @@ var cli = {
const clii = readline.createInterface({ input: process.stdin, output: process.stdout });
return new Promise((resolve, reject)=>{
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)
}
})
})
}

+ 1720
- 16585
elxr.js
File diff soppresso perché troppo grande
Vedi File


+ 1983
- 1540
i.js
File diff soppresso perché troppo grande
Vedi File


+ 170
- 63
i.win.js Vedi File

@@ -1,5 +1,9 @@

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

// var ovrrides = {
// resolve : function(v){
// if(v && v.then) return v;
@@ -18,8 +22,23 @@ var stampedFilePfx = function(date) {
}
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{
__Promise = Promise
var __require = require
var map = Array.map
// --------------------------------------------
// Node Exists. Lets launch ourselves in Node itself
@@ -43,10 +62,12 @@ try{
var selectedinstance = { root : path.resolve(".") }
__main(selectedinstance)
}
// catch(e){}
catch(e){
// // --------------------------------------------
// // Cscript
var wsh = true;
function isWin(){ return true; }
// If UCase( Right( WScript.FullName, 12 ) ) = "\CSCRIPT.EXE" Then

var clii = {
@@ -248,7 +269,7 @@ catch(e){
}
var shell = new ActiveXObject('shell.application');
var promises = [];
promises.forEach = forEach
function startPromises(){
promises.forEach(function(p){
@@ -267,6 +288,7 @@ catch(e){
var shellExec = function(cmd, argstr){
var objShell = WScript.createobject("wscript.shell")
// console.log(argstr.join( ' '))
var oExec = objShell.Exec(cmd + ' ' + argstr.join(' '))
var result = {}
var shellresult = { shell : objShell, result : result }
@@ -275,10 +297,10 @@ catch(e){
var WshFinished = 1
var WshFailed = 2
while(oExec.Status === WshRunning){
WScript.StdOut.write('.')
WScript.StdOut.write('s.')
WScript.Sleep(500)
}
var strOutput = ''
var strOutput = '\n'
switch(oExec.Status) {
case WshFinished :
strOutput = oExec.StdOut.ReadAll()
@@ -295,28 +317,29 @@ catch(e){
}
result.result = command + ' ' + cargs + ' exited with code ' + result.code
result.messages = [strOutput]
// console.log(strOutput)
// WScript.Echo(oExec.Status)
// WScript.Echo(oExec.ProcessID)
// WScript.Echo(oExec.ExitCode)

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

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

var p = null;
var pworker = function(resolve, reject){
// 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)
options = options || {
runFile : path.normalize( pfx + "out.txt")
// 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)
var args = cargs.concat()
// runFile ? (args.push(">"), args.push(runFile)) : cargs
@@ -332,7 +355,14 @@ catch(e){

var runbat = path.normalize(pfx + "run.bat")
// 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')
// WScript.Quit()
// elevatedshellexecute(runFile)
@@ -344,50 +374,59 @@ catch(e){
// // cmd /b /c
// }, 500) }

console.log(options.waitmsg || ('awaiting ' + command + ' ' + args.join(' ')))
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) {
// console.log('Wrapping up')
try {
// console.log('resolving.....................');
// console.log('--------------P' + result.messages.join(' ').trim() +'P--------------')
// if(result.messages.join().trim()) resolve(result)
// else reject(result)
resolve(result)
}
catch(e){
// console.dir(e)
if(e.message === 'Input past end of file') {
// console.log('resolving'); console.dir(result)
// console.log('---------------------------------------')
// console.dir(result)
resolve(result)
}
else {
// console.dir(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(shellresult.strOutput)
wrapup(shellresult.result)
}
// }
}
p = new Promise(pworker)
// promises.push(p)
@@ -547,7 +586,7 @@ function createPromiseClass(overrides) {
p.chain.push(thenfn)
return p;
}
, pcatch : function(catchfn) {
, 'catch' : function(catchfn) {
catchfn.isCatch = true
p.chain.push(catchfn)
return p;
@@ -578,8 +617,6 @@ function createPromiseClass(overrides) {
, resolve : resolve
, processchain : processchain
}

p['catch'] = p['pcatch']
p.chain.forEach = forEach;
return p;
}
@@ -727,13 +764,10 @@ function __main( selectedinstance ){
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 } ])
p.runFile = runFile;
var catchr = 'catch'
// console.log(p['catch'])
if(p['catch']) { catchr = 'catch' } else { catchr = 'pcatch';}
if (options.ignorefailures) {
return p.then(function(v) {
// WScript.Echo('firstThen ' + v);
return v })[catchr]( function(e) {
return v })['catch']( function(e) {
console.error(e);
// Ignore. Not a major error if where command fails !!!
throw e;
@@ -800,6 +834,26 @@ function __main( selectedinstance ){
// 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 = [
{
shellcmd: 'git',
@@ -847,7 +901,7 @@ function __main( selectedinstance ){
var self = this;
console.log('Git Installsteps called')
var ifns = [self.installcmd]
ifns.map = map;
if(!ifns.map) ifns.map = map;
return any(ifns.map(callsheltask))['catch'](function(e){
if(e.code === 1602) {
console.warn("Installation was probably cancelled.")
@@ -879,7 +933,7 @@ function __main( selectedinstance ){
, ['git', ['config', '--global', '--add', 'user.email', gitEmail]]
]
steps.map = map;
if(!steps.map) steps.map = map;
return any(steps.map(callsheltask)).then(function(){

})
@@ -897,17 +951,7 @@ function __main( selectedinstance ){
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){
@@ -916,7 +960,7 @@ function __main( selectedinstance ){
if(!repo) globalOrLocal = '--global';
else globalOrLocal = '--local'
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){
// not yet configured.
if(!result.success) return onNoResult()
@@ -930,7 +974,7 @@ function __main( selectedinstance ){
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)
return onNoResult()
})
@@ -947,7 +991,7 @@ function __main( selectedinstance ){
, install : function() {
var self = this;
var ifns = [self.installcmd]
ifns.map = map;
if(!ifns.map) ifns.map = map;
return any(ifns.map(callsheltask))['catch'](function(e){
if(e.code === 1602) {
console.warn("Installation was probably cancelled.")
@@ -956,19 +1000,7 @@ function __main( selectedinstance ){
})
}
, 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() {
var self = this;
console.log('Node preinstall steps')
@@ -991,6 +1023,81 @@ function __main( selectedinstance ){
// 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;
@@ -1000,6 +1107,6 @@ function __main( selectedinstance ){
// , downloadsdir + '/' + 'Git-2.32.0.2-64-bit.exe']).start()
promises.push(verifyAndInstallPrerequisites())

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


+ 718
- 227
index.js
File diff soppresso perché troppo grande
Vedi File


+ 2
- 2
package.json Vedi File

@@ -5,8 +5,8 @@
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build-commented": "rollup index.js --format cjs --file elxr.js",
"build": "rollup -c",
"build-elxr": "rollup index.js --format cjs --file elxr.js",
"build": "rollup -c && rollup index.js --format cjs --file elxr.js",
"index": "SET FORCE_COLOR=true && node index"
},
"keywords": [],

+ 46
- 0
repo-manifest.js Vedi File

@@ -0,0 +1,46 @@
module.exports = ((name, options)=>{

return {
reposervers : [
'http://git.bbh'
, 'https://git.bbh.org.in'
, '//172.16.0.27/repos'
, 'https://github.com'
]

// User can always add more branches and remotes as needed. Mainifest only occupies
// well defined namespaces
, remotes : [
// these are both fetch and push remotes. Use push - remotes to override push.
{ 'chess' : `${options.reposerver}/chess/elxr.git` }
, { 'public-github-baptistdev' : 'https://github.com/baptistdev/elxr.git' }
// Multiple urls dont tell us the current origin which may be
// different based on currently available/accessible based on device and client.
// We just treat them as different remotes and merge as needed.
//
, { 'origin' : `${options.reposerver}/${options.repouser}/elxr.git` }
, { 'origin-public' : `https://git.bbh.org.in/${options.repouser}/elxr.git` }
, { 'origin-unc' : `//172.16.0.27/repos/${options.repouser}/elxr.git` }
]

, 'push-remotes' : [
{ 'chess' : 'no-pushing' }
, { 'public-baptistdev' : 'no-pushing' }
, { 'public-origin' : 'no-pushing' }
]
// , 'fetch-remotes' : [] // Multiple fetch remotes are not supported by git.
// We therefore need to use
// - a pullall
// - or branch alias for multiple remote branch tracking branch strategy.
// -- This is however limited to corresponding branch names

// tracking branches.
// We at least need one branch for each remote that we wish to track.
// , 'tracking-branches' : [
// { master : ['origin/master', 'chess/master'] }
// ]
}
})

+ 0
- 4
rollup.config.js Vedi File

@@ -21,7 +21,3 @@ export default {
// exclude : [ 'chessinstances.js' ]
}), nodeResolve(), versionInjector()]
};

// Dr Kamat
// Rahul Roji
// 06259

+ 0
- 73
windowselevate.hta Vedi File

@@ -1,73 +0,0 @@

<html><HTA:APPLICATION ID="windowselevate" icon="#"/>
<script language="vbscript">
document.title = "elxr control panel"
self.ResizeTo 200,600
Sub Window_Onload
self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
End Sub

Set objShell = CreateObject("WScript.Shell")
Set objENV = objShell.Environment("Process")
dim NODE_ENV
NODE_ENV = objENV("NODE_ENV")
</script>

<script language="javascript">
//WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
// https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
// alert(windowselevate.commandLine)
var args = windowselevate.commandLine.split('"').slice(3);
// alert(args)
var processedArgs = { _ : [] }
var namedArgs = [];
for(var item in args){
if(args[item].charAt(0) === '-'){
namedArgs.push(args[item])
var split = args[item].split('=');
processedArgs[split[0].slice(2)] = split[1] || true;
}
else processedArgs._.push(args[item]);
}
// args = args.forEach(function(item){ })
// alert('processedArgs._ : ' + processedArgs._);
// alert(processedArgs.runas);
// PB : TODO -- Convert all the cli args back to string.
var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
// alert(cargs)
var shell = new ActiveXObject('shell.application');
// alert('launching node privilged. ' + processedArgs['nodepath'])
// shell.ShellExecute('where', 'node', '', '', 10);
shell.ShellExecute('node', cargs, '', 'runas', 1);
// shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
var fso = new ActiveXObject('Scripting.FileSystemObject');
window.onload = function() {
document.body.style.backgroundColor = 'black';
document.body.style.fontFamily = 'arial';
var log = document.createElement('div');
log.innerHTML='Please Wait';
function l(msg){ log.innerHTML+= msg; };
log.style.color = 'blue';
log.style.width = '95%';
log.id = 'log';
document.body.appendChild(log);
l('<Br/>Current config : ')
l('<Br/>NODE_ENV = ' + NODE_ENV)
l('<Br/>cmd = ' + processedArgs._[0])
processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
l('<Br/><Br/>')
var timer = function(){
l('.');
if(fso.FileExists("run.done")) close();
else window.setTimeout(timer, 1000);
};
window.setTimeout(timer, 3000);
};
</script>
</html>

Loading…
Annulla
Salva