2017-11-15 01:56:32 +01:00
|
|
|
use std::io;
|
2017-12-09 02:46:08 +01:00
|
|
|
use std::io::Write;
|
2018-04-13 22:46:17 +02:00
|
|
|
use std::process::Command;
|
2018-11-11 18:00:01 +01:00
|
|
|
use std::sync::Mutex;
|
2017-11-15 01:56:32 +01:00
|
|
|
|
2020-04-03 21:18:54 +02:00
|
|
|
use crate::error::print_error;
|
2019-09-13 22:26:27 +02:00
|
|
|
use crate::exit_codes::ExitCode;
|
|
|
|
|
2017-11-15 01:56:32 +01:00
|
|
|
/// Executes a command.
|
2021-08-09 09:02:30 +02:00
|
|
|
pub fn execute_command(
|
|
|
|
mut cmd: Command,
|
|
|
|
out_perm: &Mutex<()>,
|
|
|
|
enable_output_buffering: bool,
|
|
|
|
) -> ExitCode {
|
2017-11-15 01:56:32 +01:00
|
|
|
// Spawn the supplied command.
|
2021-08-09 09:02:30 +02:00
|
|
|
let output = if enable_output_buffering {
|
|
|
|
cmd.output()
|
2020-06-23 17:29:04 +02:00
|
|
|
} else {
|
2020-06-23 21:28:15 +02:00
|
|
|
// If running on only one thread, don't buffer output
|
|
|
|
// Allows for viewing and interacting with intermediate command output
|
2021-08-09 09:02:30 +02:00
|
|
|
cmd.spawn().and_then(|c| c.wait_with_output())
|
|
|
|
};
|
|
|
|
|
2017-11-15 01:56:32 +01:00
|
|
|
// Then wait for the command to exit, if it was spawned.
|
2020-06-23 17:29:04 +02:00
|
|
|
match output {
|
2017-11-15 01:56:32 +01:00
|
|
|
Ok(output) => {
|
|
|
|
// While this lock is active, this thread will be the only thread allowed
|
2017-12-09 02:46:08 +01:00
|
|
|
// to write its outputs.
|
2017-11-15 01:56:32 +01:00
|
|
|
let _lock = out_perm.lock().unwrap();
|
|
|
|
|
|
|
|
let stdout = io::stdout();
|
|
|
|
let stderr = io::stderr();
|
|
|
|
|
2020-06-23 17:29:04 +02:00
|
|
|
let _ = stdout.lock().write_all(&output.stdout);
|
|
|
|
let _ = stderr.lock().write_all(&output.stderr);
|
2019-09-13 22:26:27 +02:00
|
|
|
|
|
|
|
if output.status.code() == Some(0) {
|
|
|
|
ExitCode::Success
|
|
|
|
} else {
|
|
|
|
ExitCode::GeneralError
|
|
|
|
}
|
2017-11-15 01:56:32 +01:00
|
|
|
}
|
2018-10-03 16:48:38 +02:00
|
|
|
Err(ref why) if why.kind() == io::ErrorKind::NotFound => {
|
2020-04-03 21:18:54 +02:00
|
|
|
print_error(format!("Command not found: {:?}", cmd));
|
2019-09-13 22:26:27 +02:00
|
|
|
ExitCode::GeneralError
|
2018-10-03 16:48:38 +02:00
|
|
|
}
|
2017-11-15 23:24:11 +01:00
|
|
|
Err(why) => {
|
2020-04-03 21:18:54 +02:00
|
|
|
print_error(format!("Problem while executing command: {}", why));
|
2019-09-13 22:26:27 +02:00
|
|
|
ExitCode::GeneralError
|
2017-11-15 23:24:11 +01:00
|
|
|
}
|
2020-06-23 17:29:04 +02:00
|
|
|
}
|
2017-11-15 01:56:32 +01:00
|
|
|
}
|