@microsoft/windows-admin-center-sdk
Version:
Microsoft - Windows Admin Center Shell
79 lines (77 loc) • 3.09 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.runCommand = void 0;
const tslib_1 = require("tslib");
const logger_1 = require("./logger");
const child_process_1 = require("child_process");
const fs_1 = tslib_1.__importDefault(require("fs"));
/**
* the run command function.
* @param cmd the command to run.
* @param debug the debug flag.
* @param forceDebug the force debug flag.
* @param finalizeInfo the finalize info.
* @param writeToFileName the write to file name.
* @returns
*/
function runCommand(cmd, debug = false, forceDebug = false, finalizeInfo = undefined, writeToFileName) {
const loggerPrefix = `runCommand - ${cmd}`;
const loggerErrorPrefix = `error - runCommand - ${cmd}`;
let logString = '';
console.log(`Running ${cmd}`);
return new Promise((resolve) => {
const child = (0, child_process_1.exec)(cmd, (error, stdout, stderr) => {
if (error) {
logger_1.Logger.error(` exec error: ${error}`);
resolve(logString);
return;
}
stdout.split('\n').filter(line => line.trimEnd()).forEach(line => {
logString += `${replaceANSIEscape(line)}\n`;
logger_1.Logger.log(line, loggerPrefix);
});
stderr.split('\n').filter(line => line.trimEnd()).forEach(line => {
logString += `${replaceANSIEscape(line)}\n`;
logger_1.Logger.error(line, loggerErrorPrefix);
});
resolve(logString);
});
if (debug || forceDebug) {
child.stdout.on('data', (data) => {
data.split('\n').filter(line => line.trimEnd()).forEach(line => {
logString += `${replaceANSIEscape(line)}\n`;
logger_1.Logger.log(` ${line}`, loggerPrefix);
});
});
}
child.stderr.on('data', (data) => {
data.split('\n').filter(line => line.trimEnd()).forEach(line => {
logString += ` ${replaceANSIEscape(line)}\n`;
logger_1.Logger.error(` ${line}`, loggerErrorPrefix);
});
});
child.on('close', (code) => {
logString += `exitCode: ${code}\n`;
logger_1.Logger.log(`exitCode: ${code}`);
if (code !== 0 && finalizeInfo) {
logString += `${finalizeInfo}\n`;
logger_1.Logger.log(finalizeInfo);
}
if (writeToFileName) {
fs_1.default.writeFile(writeToFileName, logString, (writeErr) => {
if (writeErr) {
logger_1.Logger.error(`Error writing log to file: ${writeErr}`);
}
else {
console.log(`Logs saved to log'`);
}
});
}
});
});
}
exports.runCommand = runCommand;
function replaceANSIEscape(line) {
return line.replace(/\x1B\[[0-9;]*[JKmsu]/g, '');
}
//# sourceMappingURL=command-runner.js.map