aaron преди 2 години
родител
ревизия
5beabf1257
променени са 8 файла, в които са добавени 8310 реда и са изтрити 132 реда
  1. 1
    1
      bin/elxr
  2. 10
    2
      cliverse.js
  3. 3863
    0
      elxr_linux.js
  4. 60
    3
      i.win.js
  5. 355
    126
      index.js
  6. 3968
    0
      index_linux.js
  7. 19
    0
      linux.js
  8. 34
    0
      win32.js

+ 1
- 1
bin/elxr Целия файл

@@ -7,7 +7,7 @@ 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)), { env : Object.assign({}, process.env, {wd: process.cwd()}), cwd: __dirname });

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

+ 10
- 2
cliverse.js Целия файл

@@ -4,8 +4,16 @@ const fs = require('fs')
function nodeShellExec() {

var args = Array.from(arguments);
var opts = args[2] = args[2] || {}
opts.title ? null : opts.title = `${args[0]} ${args[1] }`
if(args.length > 1){
var opts = args[2] = args[2] || {}
opts.title ? null : opts.title = `${args[0]} ${args[1] }`
}
else {
opts = {
title : `${args[0]}`
// , inherit: true, shell: true
}
}
// // const spawn = require('child_process').spawn;
// const s = spawn(

+ 3863
- 0
elxr_linux.js
Файловите разлики са ограничени, защото са твърде много
Целия файл


+ 60
- 3
i.win.js Целия файл

@@ -70,6 +70,32 @@ catch(e) {
scripthostName = 'wsh'
WScript.Echo(WScript.FullName)

// WScript.Echo('--' + WScript.Arguments(0) + '--')
// WScript.Echo('------------ALL-----------')
// var argEnumerator = new Enumerator(WScript.Arguments)
// for(; !argEnumerator.atEnd(); argEnumerator.moveNext()){
// WScript.Echo('-arg-' + argEnumerator.item() + '-arg-')
// }


// // Unnamed
// WScript.Echo('------------UNNAMED-----------')
// argEnumerator = new Enumerator(WScript.Arguments.Unnamed)
// for(; !argEnumerator.atEnd(); argEnumerator.moveNext()){
// WScript.Echo('-arg-' + argEnumerator.item() + '-arg-') // Value
// }

// // Named
// WScript.Echo('------------NAMED-----------')
// argEnumerator = new Enumerator(WScript.Arguments.Named)
// for(; !argEnumerator.atEnd(); argEnumerator.moveNext()){
// // WScript.Echo('-arg-' + argEnumerator.item(argEnumerator) + '-arg-') // Key
// WScript.Echo('-key-' + argEnumerator.item() + '-key-') // Key
// WScript.Echo('-val=' + WScript.Arguments.Named(argEnumerator.item()) + '=val-') // Value
// }

var all = WScript.Arguments.Named('all');
console = {
log : function(m) { WScript.Echo(m)}
, error : function(m) {WScript.Echo(m) }
@@ -819,6 +845,7 @@ function __main( selectedinstance ){
var downloadtasks = [];
var installtasks = [];
prerequisites.forEach(function(preq) {
if(!all && preq.optional) return
var p = preq.exists().then(function(exists) {
if (exists) console.log( preq.shellcmd + ' exists');
else {
@@ -890,8 +917,10 @@ function __main( selectedinstance ){
// var ENV = Object.assign({}, process.env); // Shallow clone it.
var WshShell = WScript.CreateObject("WScript.Shell")
var ENV = WshShell.Environment("Process")
WScript.echo( ENV("Path") )
// WScript.echo( ENV("Path") )
function sysAddPathVar(path){

return true; // PB : TODO -- Not yet enabled. Remove sys path from path before saving.
// Object.assign({
// inherit: true, shell: true, env: ENV, title: `${command} ${args}`
// }, options)
@@ -1078,6 +1107,7 @@ function __main( selectedinstance ){
}
, {
shellcmd: 'python2'
, optional : true
, url: 'https://www.python.org/ftp/python/2.7.18/python-2.7.18.amd64.msi'
, installer: 'python-2.7.18.amd64.msi'
, installcmd: ['MSIEXEC.exe', ['/i'
@@ -1101,8 +1131,35 @@ function __main( selectedinstance ){
, postinstallsteps : function() { return sysAddPathVar('%USERPROFILE%\\AppData/Local\\Microsoft\\WindowsApps') }
, exists : exists
}
,
{
, {
shellcmd: 'code'
, optional : true
, url: 'https://vscode-update.azurewebsites.net/latest/win32-x64/stable'
, installer: 'vscode-win32-x64-latest-stable.exe'
, installcmd: ['cmd', ['/c', 'start',
'/WAIT', downloadsdir + '/' + 'Git-2.33.0.2-64-bit.exe'
, '/VERYSILENT'
// , '/MERGETASKS=!runcode' // This is required only for vscode...
]]
, preinstallsteps : function() { return Promise.resolve(true) }
, install : function() {
var self = this;
var ifns = [self.installcmd]
if(!ifns.map) ifns.map = map;
console.log('Installing')
return any(ifns.map(callsheltask))['catch'](function(e){
if(e.code === 1602) {
console.warn("Installation was probably cancelled.")
}
else throw e
}).then(function(){
return self.postinstallsteps()
})
}
, postinstallsteps : function() { return sysAddPathVar('%USERPROFILE%\\AppData/Local\\Microsoft\\WindowsApps') }
, exists : exists
}
, {
shellcmd: 'elxr'
, installcmd: [ isWin() ? 'npm.cmd' : 'npm' , ['link'], { cwd : selectedinstance.root + '\\elxr' /* cwd should be the cloned dir*/}]
, preinstallsteps: function() {

+ 355
- 126
index.js Целия файл

@@ -11,8 +11,6 @@ var chalk = require('chalk')
const homedir = require('os').homedir();


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

function sysAddPathVar(path){
// Object.assign({
// inherit: true, shell: true, env: ENV, title: `${command} ${args}`
@@ -32,12 +30,30 @@ var getCredentials = function(){
var creds = fs.readFileSync(path.normalize(`${homedir}/.elxrcredentials`), { encoding: 'utf8' });
var creds = creds.split('\n').map( c => c.trim() && new URL(c));
console.log(creds);
creds.forEach(cred => {console.log( cred.hostname ); console.log( cred.username )} );

// Subsequent calls
getCredentials = ()=>{ return creds }
return getCredentials();
}

function getCurrentFolder(){
var tasks = [
// () => {
// // Use junctions to avoid npm package issues
// var p = nodeShellExec('cd').then((result)=>{
// console.dir(result)
// }).catch((e) => { console.error(e) })
// return p;
// }
()=>{
return Promise.resolve(process.cwd())
}
];

return any(tasks);
}

const __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b'
const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
const runtimestamp = (new Date()).getTime();
@@ -100,6 +116,22 @@ const fs = require('fs')

const cliargs = utils.cliargs;
const processedArgs = cliargs(process.argv.slice(2));
if(!processedArgs.wd){
if(process.env.wd){
}
else {
process.env.wd = process.cwd();
if(process.cwd() === __dirname) {
// This script was launched in the same dir.
}
}
}
else process.env.wd = processedArgs.wd
var ENV = Object.assign({}, process.env); // Shallow clone it.



console.dir(processedArgs)
// PB : TODO -- defaults for valuless arguments if passed.
// Object.keys(processedArgs).forEach(a=>{
@@ -126,6 +158,76 @@ const dirs = async (perform, path) => {
}
}



var templateprocess = function(str, substitutes){
const regex = /__(.*?)__/gm;
// const str = `__link____instance__server-lib__name__`;
let m;

return str.replace(regex, function(match, key) {
console.log(`Found match, group ${match}: ${key}`);
return substitutes[key] || match;
})

// while ((m = regex.exec(str)) !== null) {
// // This is necessary to avoid infinite loops with zero-width matches
// if (m.index === regex.lastIndex) {
// regex.lastIndex++;
// }
// var rstr = str;
// // The result can be accessed through the `m`-variable.
// m.forEach((match, groupIndex) => {
// // rstr = rstr.replace( groupIndex
// console.log(`Found match, group ${groupIndex}: ${match}`);
// if(groupIndex === 0) return
// });

// }

}

function copyFileSync( source, target , options) {

var targetFile = target;

// If target is a directory, a new file with the same name will be created
if ( fs.existsSync( target ) ) {
if ( fs.lstatSync( target ).isDirectory() ) {
targetFile = path.join( target, path.basename( source ) );
}
}

fs.writeFileSync(targetFile, fs.readFileSync(source));
}

function copyFolderRecursiveSync( source, target, options ) {
var files = [];

// Check if folder needs to be created or integrated
var targetFolder = path.join( target, path.basename( source ) );
if ( !fs.existsSync( targetFolder ) ) {
fs.mkdirSync( targetFolder );
}

// Copy
if ( fs.lstatSync( source ).isDirectory() ) {
files = fs.readdirSync( source );
files.forEach( function ( file ) {
var curSource = path.join( source, file );
if ( fs.lstatSync( curSource ).isDirectory() ) {
copyFolderRecursiveSync( curSource, targetFolder );
} else {
copyFileSync( curSource, targetFolder );
}
} );
}
}

var getShellTask = (command, args, options) => {
options = options || {}
var callshell = command === 'rm' ? getgitbashtask : getshelltask;
@@ -502,7 +604,7 @@ var op = {

if (__isElevated) {
try {
op[processedArgs.label || processedArgs._[0] || 'undefined']()
op[processedArgs.label || processedArgs._[0] || 'undefined'](processedArgs)
}
catch (e) {
console.error('Error Invalid command : ' + e)
@@ -526,11 +628,16 @@ var op = {
console.log('result : ' + JSON.stringify(r))
Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; })
// PB : TODO -- Convert all the cli args back to string.
var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._)
namedArgs.length > 0 ? args = args.concat(namedArgs.join(' ')) : null;
args.push('--runas=self');
// args.push('--nodepath=' + r.messages[r.messages.length - 1])
// if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
// if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
console.dir(processedArgs)
// console.dir(processedArgs._)
// console.dir(namedArgs.join(' '))
console.dir(args)
// throw 'test'

return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
, {
@@ -1512,6 +1619,8 @@ var op = {
}
else return op['runas']()
}


, 'use' : () => {
// use a certain named instance.
// Eg :
@@ -1785,10 +1894,11 @@ var op = {
// 2nd use Pharmacy needs justification Form.
// Approval after a certain period of time.
}
, 'g': () => {
, 'g' : () => {
if (processedArgs.h) {

console.log('elxr g [modelname] => generate a model named [modelname]');
console.log('elxr g model [modelname] => generate a model named [modelname]');
console.log('elxr g vmodel [modelname] => generate a model named [modelname]');
console.log('elxr g => regenerate all known models');
return
}
@@ -1885,6 +1995,20 @@ var op = {

}

, 'undefined' : ()=>{
console.warn('Are you sure you want to refresh all the models.');
throw 'NOT YET IMPLMENTED'
}

, 'vmodel' : ()=>{
var verse = [ '__universe__/vmodel' ]

// console.dir(templateprocess(`__link____instance__server-lib__name__`, { link( ){
// return processed }, instance : 'elixir-', name : 'newmodel' } )
// )

}

}

g[processedArgs._[1]]();
@@ -1959,6 +2083,68 @@ var cmds = {
, cmd : 'users list'
, noprerequisites : true
}
, 'g' : {
cmdFn : op['g'] // default
, cmd : 'g'
, noprerequisites : true
, getPossiblePrompts(){ return {} }
}
, 'link' : {
'cmd' : 'link'
// , cmdFn : function( sourecpath, filename, dir ){
// var afterTargetPath = (dir)=>{
// console.dir(dir);

// // var tasks = [
// // () => {
// // // Use junctions to avoid npm package issues
// // var p = nodeShellExec('mklink', ['/J', filename, sourecpath], {
// // inherit: true, shell: true
// // , cwd : dir || instanceroot
// // , env: process.env
// // }).catch((e) => { console.error(e) })
// // return p;
// // }
// // ];

// }
// // console.dir(process.env)
// if(!dir) getCurrentFolder().then(afterTargetPath);
// else afterTargetPath(dir)

// }
, cmdFn : function( cmdopts ){
// sourecpathandfile should include name of file name
targetfilename = cmdopts.targetfilename || processedArgs._[1]
// console.log(processedArgs)
if(!targetfilename) return Promise.reject('error no file provided for linking')
targetdir = cmdopts.targetdir || process.env.wd
sourecpathandfile = cmdopts.sourecpathandfile || path.normalize(`../../node_modules/chess-server-lib/common/models/${targetfilename}`)

var tasks = [
() => {
// Use junctions to avoid npm package issues
var p = nodeShellExec('mklink', [path.normalize(`${targetdir + '/' + targetfilename}`), sourecpathandfile], {
inherit: true, shell: true
, cwd : targetdir
, env: process.env
}).catch((e) => { console.error(e) })
return p;
}
];
if (__isElevated) {
return any(tasks).then(() => {
fs.writeFileSync('run.done', 'success')
}).catch(() => {
fs.writeFileSync('run.done', 'error')
})
}
else return op['runas']()
}
, noprerequisites : true
, privileged : true
}
}

var elxrcmd = (function(){
@@ -1976,8 +2162,8 @@ var elxrcmd = (function(){
function __createO(o){
if(o.finalized) return o;
var subs = Object.keys(cmds[o.cmd].subcommands || {})
console.log(subs)
console.log(o)
// console.log(subs)
// console.log(o)
subs.forEach(sub=>elxrcmd.create( cmds[subcommandlabelFor(o.cmd, sub)] ))
var created = utils.assign_strict({}, __cmd, cmds[o.cmd], o)
@@ -1995,6 +2181,8 @@ var elxrcmd = (function(){
})()

elxrcmd.create(cmds['users'])
elxrcmd.create(cmds['g'])
elxrcmd.create(cmds['link'])

var interpretrun = function(){

@@ -2573,10 +2761,39 @@ var __acquireData = function (selected, owner, clusternodename, datarepo, errHan
})
}

var launchpath = path.normalize(process.cwd())
var launchpath = path.resolve(path.normalize(process.env.wd))
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....
var instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
// path.dirname(launchpath).split(path.sep).pop()

var parent = path.dirname(launchpath);
var pp = launchpath;
var instancediscoverytasks = [];
while(parent !== pp){
instancediscoverytasks.push(
((pa)=>{
var p = pa;
return function(){
return hasElxr(p).then((value)=>{
if(value) return p
throw { value : false };
})
}
})(pp)
)
pp = parent;
parent = path.dirname(parent);
}

var instanceroot = null
var detectInstanceRoot = any(instancediscoverytasks, true, true).then( ir => {
if(ir.error) { instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ; }
else instanceroot = ir.pVal
return instanceroot
}).catch(()=>{
instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
})


// PB : TODO -- Embed this in the build instead of inlining it.
// Also attepmt to load from ../chess-config/...
@@ -2667,7 +2884,7 @@ var __default = ((name, options)=>{
, { repo : 'loopback-jsonapi-model-serializer' }
, { repo : 'loopback-connector-mysql' }
, { repo : 'loopback-connector-ds' }
, { repo : 'chess-server-lib' }
, { repo : 'ember-service-worker' }
, { repo : 'ember-service-worker-asset-cache' }
, { repo : 'ember-service-worker-cache-fallback' }
@@ -2676,7 +2893,7 @@ var __default = ((name, options)=>{
, { repo : 'global-this' }
]

, elevated : [ ]
, elevated : [ { repo : 'chess-server-lib' } ]
, exludeMergeRepos : { }
}

@@ -2859,10 +3076,10 @@ var getBoundEachPrompt = function(target, possiblePrompts, promptables, choices,
// console.log(k)
// console.dir(possiblePrompts); //console.dir(target)
prompts.push(async ()=>{
// PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
// We take a snapshot... Shallow.. !! If required deep should be used based on use case.
// If latest altered state is required we can reerence this directly.
// PB : NOTE -- Important in async cases when this {{target}} needs to be in the same state as when it was invoked.
// We need to take a snapshot... Shallow.. !! If required deep should be used based on use case.
// var asyncthis = Object.assign(this);
// By default Latest altered state is provided which is an implicit reference directly.
promptables[k].choices = choices[k]
Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
return await target[k]
@@ -3111,101 +3328,6 @@ function ensureDirectoryExistence(filePath) {

var mainTasks = [];
function verifyAndInstallPrerequisites() {
fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
// PB : TODO include and build from files... using rollup..
var downloadbatch =
`::**************************************************************************
:Download_ <url> <File>
Powershell.exe ^
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
(New-Object System.Net.WebClient).DownloadFile('%1','%2')
exit /b
::**************************************************************************`
fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch)

var windowselevate =
`
<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('cmd.exe', '/k notepad.exe', '', 'runas', 1);
// shell.ShellExecute('cmd.exe ', '/k node "' + cargs + '"', '', 'runas', 1);
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>
`
fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate)

var downloadtasks = [];
var installtasks = [];
prerequisites.forEach(preq => {
@@ -3789,6 +3911,111 @@ var maintask = () => {

}

var generateDependencies = function(){
// PB : TODO -- Keep only the last n runs...
// Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!

ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
// PB : TODO include and build from files... using rollup..
var downloadbatch =
`::**************************************************************************
:Download_ <url> <File>
Powershell.exe ^
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
(New-Object System.Net.WebClient).DownloadFile('%1','%2')
exit /b
::**************************************************************************`
fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch)

var windowselevate =
`
<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 = [];
namedArgs.push('--wd=' + objENV('wd'))
// alert(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);
// alert(objENV('wd'))
// PB : TODO -- Convert all the cli args back to string.
// __filename will sure we are launhed using the same entry point.
var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' ${__filename.replace(/\\/g, '\\\\')} ' + 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('cmd.exe', '/k notepad.exe', '', 'runas', 1);
// shell.ShellExecute('cmd.exe ', '/k node "' + cargs + '"', '', 'runas', 1);
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>
`
fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate)
}

var startElxr = function() {
const retaincount = 2
var min = runtimestamp;
@@ -3860,6 +4087,7 @@ var startElxr = function() {
})
.then(()=>{

generateDependencies();
if(noprerequisites[processedArgs._[0]]
|| skipprereqs[processedArgs._[0]]
) {
@@ -3879,7 +4107,8 @@ var startElxr = function() {
else collect.push(matches[1])
}
}, `${selectedinstance.root}/.elxr` ).then(()=>{
}, `${selectedinstance.root}/.elxr` )
.then(()=>{
// delete garbage
if(collect.length > retaincount) {
@@ -3891,24 +4120,24 @@ var startElxr = function() {
}
else return true
})
.then(()=>{
if (!skipprerequisites && !__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
mainTasks.push(maintask)
return any(mainTasks);
})
}
else {
if (!skipprerequisites && !__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
mainTasks.push(maintask)
return any(mainTasks);
}
else return true;
})
.then(()=>{
// PB : TODO -- Keep only the last n runs...
// Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
if (!skipprerequisites && !__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
mainTasks.push(maintask)
return any(mainTasks);
})
}

acquireElevationState().then(() => {
return startElxr()
detectInstanceRoot.then(()=>{
return acquireElevationState().then(() => {
return startElxr()
})
})

// detect if alread installed -> Take no action.

+ 3968
- 0
index_linux.js
Файловите разлики са ограничени, защото са твърде много
Целия файл


+ 19
- 0
linux.js Целия файл

@@ -0,0 +1,19 @@
module.exports = {
verifyAndInstall() {
return Promise.resolve(true);
}

, acquireElevationState(__isElevated) {
//__isElevated = false;
if (__isElevated === null) { return Promise.resolve(__isElevated) }
else
return Promise.resolve(__isElevated);
}

, verifyAndInstallPrerequisites() {
return Promise.resolve(true);
}
, whichOS() {
console.log("OS - Linux");
}
};

+ 34
- 0
win32.js Целия файл

@@ -0,0 +1,34 @@
module.exports = {
verifyAndInstall(){
return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
if(exists) {
// return any(['git', ['config', '--global', '-l']].map(getshelltask))
return this.postinstallsteps.bind(this)()
}
return this.install();
});
},

acquireElevationState(__isElevated) {
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');
return false;
});
}
else return Promise.resolve(__isElevated);
},

}


Loading…
Отказ
Запис