shell: no need to promise scoping

This commit is contained in:
Girish Ramakrishnan
2024-02-21 19:40:27 +01:00
parent cfd5c0f82b
commit a6f078330f
20 changed files with 105 additions and 107 deletions
+18 -20
View File
@@ -8,11 +8,12 @@ const assert = require('assert'),
util = require('util');
exports = module.exports = {
exec,
execArgs,
sudo,
promises: {
exec: util.promisify(exec),
execArgs: util.promisify(execArgs),
sudo: util.promisify(sudo)
}
};
@@ -20,46 +21,43 @@ exports = module.exports = {
const SUDO = '/usr/bin/sudo';
// default encoding utf8, no shell, separate args
function execArgs(tag, file, args, options, callback) {
async function execArgs(tag, file, args, options) {
assert.strictEqual(typeof tag, 'string');
assert.strictEqual(typeof file, 'string');
assert(Array.isArray(args));
assert.strictEqual(typeof options, 'object');
assert.strictEqual(typeof callback, 'function');
debug(`${tag} exec: ${file}`);
const execOptions = Object.assign({ encoding: 'utf8', shell: false }, options);
// https://github.com/nodejs/node/issues/25231
const cp = child_process.execFile(file, args, execOptions, function (error, stdout, stderr) {
let e = null;
if (error) {
e = new BoxError(BoxError.SHELL_ERROR, `${tag} errored with code ${error.code} message ${error.message}`);
return new Promise((resolve, reject) => {
const cp = child_process.execFile(file, args, execOptions, function (error, stdout, stderr) {
if (!error) return resolve(stdout);
const e = new BoxError(BoxError.SHELL_ERROR, `${tag} errored with code ${error.code} message ${error.message}`);
e.stdout = stdout; // when promisified, this is the way to get stdout
e.stderr = stderr; // when promisified, this is the way to get stderr
debug(`${tag}: ${file} with args ${args.join(' ')} errored`, error);
reject(e);
});
// https://github.com/nodejs/node/issues/25231
if (options.input) {
cp.stdin.write(options.input);
cp.stdin.end();
}
callback(e, stdout);
});
if (options.input) {
cp.stdin.write(options.input);
cp.stdin.end();
}
}
// default encoding utf8, shell, handles input, full command
function exec(tag, cmd, options, callback) {
async function exec(tag, cmd, options) {
assert.strictEqual(typeof tag, 'string');
assert.strictEqual(typeof cmd, 'string');
assert.strictEqual(typeof options, 'object');
assert.strictEqual(typeof callback, 'function');
const [file, ...args] = cmd.split(' ');
execArgs(tag, file, args, options, callback);
return await execArgs(tag, file, args, options);
}
// use this when you are afraid of how arguments will split up