unity-builder/src/model/system.ts

66 lines
1.6 KiB
TypeScript
Raw Normal View History

import { core, exec } from '../dependencies.ts';
class System {
2022-02-01 02:31:20 +00:00
static async run(command, arguments_: any = [], options = {}, shouldLog = true) {
let result = '';
let error = '';
2020-05-01 11:57:42 +00:00
let debug = '';
const listeners = {
stdout: (dataBuffer) => {
result += dataBuffer.toString();
},
stderr: (dataBuffer) => {
error += dataBuffer.toString();
},
debug: (dataString) => {
2020-05-01 11:57:42 +00:00
debug += dataString.toString();
},
};
2020-05-21 18:40:03 +00:00
const showOutput = () => {
2022-02-01 02:31:20 +00:00
if (debug !== '' && shouldLog) {
log.debug(debug);
2020-05-21 18:40:03 +00:00
}
2020-05-01 11:57:42 +00:00
2022-02-01 02:31:20 +00:00
if (result !== '' && shouldLog) {
log.info(result);
2020-05-21 18:40:03 +00:00
}
2020-05-01 11:57:42 +00:00
2022-02-01 02:31:20 +00:00
if (error !== '' && shouldLog) {
log.warning(error);
2020-05-21 18:40:03 +00:00
}
};
2020-05-01 11:57:42 +00:00
const throwContextualError = (message: string) => {
2020-05-21 18:40:03 +00:00
let commandAsString = command;
if (Array.isArray(arguments_)) {
2020-05-21 18:40:03 +00:00
commandAsString += ` ${arguments_.join(' ')}`;
} else if (typeof arguments_ === 'string') {
commandAsString += ` ${arguments_}`;
}
2020-05-21 18:40:03 +00:00
throw new Error(`Failed to run "${commandAsString}".\n ${message}`);
};
try {
if (command.trim() === '') {
throw new Error(`Failed to execute empty command`);
}
2022-06-23 21:25:56 +00:00
const { exitCode } = await exec(command, arguments_, { silent: true, listeners, ...options });
2020-05-21 18:40:03 +00:00
showOutput();
if (exitCode !== 0) {
2020-05-21 23:24:22 +00:00
throwContextualError(`Command returned non-zero exit code.\nError: ${error}`);
2020-05-21 18:40:03 +00:00
}
} catch (inCommandError) {
showOutput();
2020-05-21 23:24:22 +00:00
throwContextualError(`In-command error caught: ${inCommandError}`);
2020-05-21 18:05:06 +00:00
}
return result.replace(/\n+$/, '');
}
}
export default System;