瀏覽代碼

Merge branch 'master' of /repos/elxr

master
Pradeep Bhaskaran 4 年之前
父節點
當前提交
b06081ab09
共有 4 個檔案被更改,包括 178 行新增43 行删除
  1. 1
    0
      .gitignore
  2. 109
    42
      index.js
  3. 4
    1
      package.json
  4. 64
    0
      windowselevate.hta

+ 1
- 0
.gitignore 查看文件

@@ -0,0 +1 @@
/node_modules

+ 109
- 42
index.js 查看文件

@@ -84,18 +84,26 @@ function any(iterable, continueOnFailure) {
);
}

var __isElevated = null;
var isRunningElevated = ()=>{
return nodeShellExec( "fsutil", ["dirty", "query", "C:"], {
inherit : true, shell: true
, env: process.env
, title : `check privileged execution mode using fsutil dirty query C:`
}).then((exitcode)=>{
console.log('Elevated')
return true;
}).catch(()=>{
console.log('Not Elevated');
throw false;
});
if(__isElevated === null) {
return nodeShellExec( "fsutil", ["dirty", "query", "C:"], {
inherit : true
// , shell: true
// , stdio: 'ignore'
, env: process.env
, title : `check privileged execution mode using "fsutil dirty query C:"`
}).then((exitcode)=>{
console.log('Elevated')
__isElevated = true;
return true;
}).catch(()=>{
__isElevated = false;
console.log('Not Elevated');
throw false;
});
}
else return Promise.resolve(__isElevated);
}


@@ -154,12 +162,16 @@ var elevatedRunasRepos = [
, 'chess-server'
]

var productionRepos = [
'elixir-config-production'
]

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

var op = {
'h' : ()=>{ console.log(cli + ' ' + ver + ' ' + help); return '-h' }
, 'undefined' : ()=>{ return op.h(); }
, 'upgrade' : ()=>{
console.log('upgrade.......')
var tasks = [
@@ -235,25 +247,55 @@ var __runcmd = function(label){
})
}
, 'runas' : ()=>{
return isRunningElevated().then(() => op[ processedArgs.label || processedArgs._[0] || 'h']() )
return isRunningElevated().then(
(isElevated) => {
if(isElevated) {
try {
op[ processedArgs.label || processedArgs._[0] || 'h']()
}
catch(e){
console.error('Error Invalid command : ' + e)
fs.writeFileSync('run.done', 'success')
}
finally {
}
} else throw false;
}
)
.catch(()=>{
console.log('Not Elevated');
console.dir(processedArgs)
console.log('Not Elevated Requesting Elevated Privileges');
// Wait for the runas to complete before we read it.
try {
fs.unlinkSync('run.done')
fs.unlinkSync('run.log')
}
catch(e) { } //Ignore
// PB : TODO -- Convert all the cli args back to string.
var namedArgs = [];
Object.keys(processedArgs).forEach((v)=>{ v!='_' ? namedArgs.push('--'+v+'='+processedArgs[v]) : null; })
var cargs = `${processedArgs.debug ? '--inspect-brk' : ''} --inspect-brk elxr ${processedArgs._.join(' ')} ${namedArgs.join(' ') } --runas=true`
console.log('Requesting Elevated Privileges for : ' + `node ${cargs}`)
// fs.writeFileSync('runas.js', `javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('node', '${cargs}', '', 'runas', 1);close();`)
nodeShellExec('MSHTA', [`javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('node', '${cargs}', '', 'runas', 1);close();`]
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var args = [__dirname + '/windowselevate.hta'].concat(processedArgs._); args.push('--runas')
nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
, {
// inherit : true
// , shell: true
// cwd : process.env.pwd
inherit : true
,
shell: true
// ,
env: process.env
, env: process.env
, runas : true
, title : `runas`
}
);
).then(()=>{
// runas returned.
var runaslog = JSON.parse('[ { "success" : true, "result" : "runas Log" }' + fs.readFileSync('run.log', { flags : 'a+'}) + ']');
runaslog.forEach((logEntry)=>{
logEntry.succes ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' '))
})
})
.catch(err => console.error('Elevation failed : ' + err));
})
}
, 'push' : ()=>{
@@ -338,19 +380,21 @@ var __runcmd = function(label){
var performPull = repo => {
if(existsSync(repo)) {
console.log('pulling ' + repo)
nodeShellExec('git', ['pull'], {
return nodeShellExec('git', ['pull'], {
inherit : true, shell: true,
cwd : repo
// , env: process.env
, runas : processedArgs.runas
, title : `git pull ${repo}`
}).catch((e)=>{ console.error(e) })
}
else {
console.log('cloning ' + repo)
nodeShellExec('git', ['clone', '//172.16.0.27/repos/' + repo + '.git'],
return nodeShellExec('git', ['clone', '//172.16.0.27/repos/' + repo + '.git'],
{
inherit : true, shell: true,
env: process.env
, runas : processedArgs.runas
, title : `git clone ${'//172.16.0.27/repos/' + repo + '.git'}`
}).catch((e)=>{ console.error(e) })
}
@@ -358,11 +402,21 @@ var __runcmd = function(label){

if(!processedArgs.runas) gitRepos.forEach(performPull)
return isRunningElevated().then(
()=> elevatedRunasRepos.forEach(performPull))
.catch(
() => op['runas']()
(isElevated) => {
if(isElevated) {
any(elevatedRunasRepos.map((repo)=>performPull(repo))).then(()=>{
fs.writeFileSync('run.done', 'success')
}).catch(()=>{
fs.writeFileSync('run.done', 'error')
})
}
else throw false;
}
).catch(
() => {
op['runas']()
}
)
}
, 'npmi' : ()=>{
var tasks = [];
@@ -398,7 +452,7 @@ var __runcmd = function(label){
console.log('Starting Elixir Server.');
var env = Object.assign({}, process.env); // Shallow clone it.
// console.dir(env)
env.NODE_ENV = label || 'development';
env.NODE_ENV = process.env.NODE_ENV || 'development';
env.DEBUG = 'loopback:connector:' + dbForLabel(label)
var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
// cmd = 'node'
@@ -528,7 +582,11 @@ var __runcmd = function(label){
]
)
}
any(tasks)
any(tasks).then(()=>{
fs.writeFileSync('run.done', 'success')
}).catch(()=>{
fs.writeFileSync('run.done', 'error')
})

// Antibiotic stewardship program.
// 1st use is fine.
@@ -588,7 +646,7 @@ var __runcmd = function(label){
g[processedArgs._[1]]();
}
}
return op[label] ? op[label]() : op['start'](label);
return op[label] ? op[label]() : null;
}

// mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
@@ -597,34 +655,43 @@ var __runcmd = function(label){
var mysql = '../xampp/mysql/bin/mysql'
var mysqldump = '../xampp/mysql/bin/mysqldump'

__runcmd(processedArgs.label || processedArgs._[0] || 'h');
// nodeShellExec('git', ['status']);
// --runas
if(processedArgs.runas) {
// Weve been asked to run in priviledged mode. Check if we already are privileged.
__runcmd('runas')
}
else __runcmd(processedArgs.label || processedArgs._[0] || 'h');

function nodeShellExec() {

var args = Array.from(arguments);
args[2] ? null : args[2] = {}
args[2].title ? null : args[2].title = `${args[0]} ${args[1]}`
var opts = args[2] = args[2] || {}
opts.title ? null : opts.title = `${args[0]} ${args[1] }`
const child = spawn(...arguments);

var p = new Promise(function(resolve, reject){
if(!args[2].detached) {
if(!opts.detached) {
var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
var succes = true;
// use child.stdout.setEncoding('utf8'); if you want text chunks
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
child.on('error', (chunk) => { messages.push(chunk); /*console.error(chunk)*/ });
child.on('error', (chunk) => { succes = false; messages.push(chunk); /*console.error(chunk)*/ });
child.stderr.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
// child.stderr.pipe(process.stderr);
child.on('close', (code) => {
console.log([` ${args[2].title} exited with code ${code}`])
// console.log([ messages.join('') ])
process.stdout.write( messages.join('') )
if(code !== 0 ) return reject(code)
if(code !== 0) succes = false;
if(opts.runas){
fs.writeFileSync('run.log', ', ' + JSON.stringify({ result: ` ${opts.title} exited with code ${code}`, messages : messages }), {'flag':'a+'} )
}
else {
succes ? console.log(['success : ' + ` ${opts.title} exited with code ${code}`]) : console.error([`error : ${opts.title} exited with code ${code}`])
// console.log( messages.join('') )
process.stdout.write( messages.join('') )
}
if(code !== 0) return reject(code)
resolve(true)
});
}

+ 4
- 1
package.json 查看文件

@@ -8,5 +8,8 @@
},
"keywords": [],
"author": "",
"license": "ISC"
"license": "ISC",
"dependencies": {
"tree-kill": "^1.2.2"
}
}

+ 64
- 0
windowselevate.hta 查看文件

@@ -0,0 +1,64 @@

<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">
// alert(NODE_ENV);
//WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
// alert(windowselevate.commandLine)
var args = windowselevate.commandLine.split('"').slice(3);
// alert(args)
var processedArgs = { _ : [] }
for(var item in args){
// alert(args[item].charAt(0))
args[item] ? args[item].charAt(0) === '-' ? processedArgs[args[item].slice(2)] = args[item].split('=')[1] || true : processedArgs._.push(args[item]) : null
}
// args = args.forEach(function(item){ })
// alert('processedArgs._ : ' + processedArgs._);
// alert(processedArgs.runas);
var namedArgs = [];
// Object.keys(processedArgs).forEach( function(v){ v!='_' ? namedArgs.push('--'+v+'='+processedArgs[v]) : null; })
var cargs = (processedArgs.debug ? '--inspect-brk' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ') + ' ' + ' --runas=true';
var shell = new ActiveXObject('shell.application');
shell.ShellExecute('node', 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');
function l(msg){ log.innerHTML+= msg; };
log.style.color = 'blue';
log.id = 'log';
document.body.appendChild(log);
log.innerHTML='Please Wait';
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…
取消
儲存