balena-cli
Version:
The official balena Command Line Interface
63 lines • 2.38 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.executeWithPrivileges = executeWithPrivileges;
const child_process_1 = require("child_process");
const lazy_1 = require("./lazy");
async function executeWithPrivileges(command, stderr, isCLIcmd = true) {
const isElevated = await (await Promise.resolve().then(() => require('is-elevated')))();
const { shellEscape } = await Promise.resolve().then(() => require('./helpers'));
const opts = {
env: process.env,
stdio: ['inherit', 'inherit', stderr ? 'pipe' : 'inherit'],
};
if (isElevated) {
if (isCLIcmd) {
command = [process.argv[0], process.argv[1], ...command];
}
await spawnAndPipe(command[0], command.slice(1), opts, stderr);
}
else {
if (isCLIcmd) {
command = process.pkg
? [process.argv[0], ...command]
: [process.argv[0], process.argv[1], ...command];
}
opts.shell = true;
const escapedCmd = shellEscape(command);
if (process.platform === 'win32') {
await windosuExec(escapedCmd, stderr);
}
else {
await spawnAndPipe('sudo', escapedCmd, opts, stderr);
}
}
}
async function spawnAndPipe(spawnCmd, spawnArgs, spawnOpts, stderr) {
await new Promise((resolve, reject) => {
const ps = (0, child_process_1.spawn)(spawnCmd, spawnArgs, spawnOpts);
ps.on('error', reject);
ps.on('exit', (codeOrSignal) => {
if (codeOrSignal !== 0) {
const errMsgCmd = `[${[spawnCmd, ...spawnArgs].join()}]`;
reject(new Error(`Child process exited with error code "${codeOrSignal}" for command:\n${errMsgCmd}`));
}
else {
resolve();
}
});
if (stderr && ps.stderr) {
ps.stderr.pipe(stderr);
}
});
}
async function windosuExec(escapedArgs, stderr) {
if (stderr) {
const msg = (0, lazy_1.stripIndent) `
Error: unable to elevate privileges. Please run the command prompt as an Administrator:
https://www.howtogeek.com/194041/how-to-open-the-command-prompt-as-administrator-in-windows-8.1/
`;
throw new Error(msg);
}
return require('windosu').exec(escapedArgs.join(' '));
}
//# sourceMappingURL=sudo.js.map