Skip to content
Myr

command.rs

This file

Path

src/exec/command.rs

110 lines · 3.1 KiB · Rust

Last changed by

Merge pull request #1627 from hamirmahal/style/simplify-string-formatting-for-readabilityThayne McCombsbefore adoption202e329

History of this file

Take it

1use std::io;2use std::io::Write;3use std::sync::Mutex;45use argmax::Command;67use crate::error::print_error;8use crate::exit_codes::ExitCode;910struct Outputs {11    stdout: Vec<u8>,12    stderr: Vec<u8>,13}14struct OutputBuffer<'a> {15    output_permission: &'a Mutex<()>,16    outputs: Vec<Outputs>,17}1819impl<'a> OutputBuffer<'a> {20    fn new(output_permission: &'a Mutex<()>) -> Self {21        Self {22            output_permission,23            outputs: Vec::new(),24        }25    }2627    fn push(&mut self, stdout: Vec<u8>, stderr: Vec<u8>) {28        self.outputs.push(Outputs { stdout, stderr });29    }3031    fn write(self) {32        // avoid taking the lock if there is nothing to do33        if self.outputs.is_empty() {34            return;35        }36        // While this lock is active, this thread will be the only thread allowed37        // to write its outputs.38        let _lock = self.output_permission.lock().unwrap();3940        let stdout = io::stdout();41        let stderr = io::stderr();4243        let mut stdout = stdout.lock();44        let mut stderr = stderr.lock();4546        for output in self.outputs.iter() {47            let _ = stdout.write_all(&output.stdout);48            let _ = stderr.write_all(&output.stderr);49        }50    }51}5253/// Executes a command.54pub fn execute_commands<I: Iterator<Item = io::Result<Command>>>(55    cmds: I,56    out_perm: &Mutex<()>,57    enable_output_buffering: bool,58) -> ExitCode {59    let mut output_buffer = OutputBuffer::new(out_perm);60    for result in cmds {61        let mut cmd = match result {62            Ok(cmd) => cmd,63            Err(e) => return handle_cmd_error(None, e),64        };6566        // Spawn the supplied command.67        let output = if enable_output_buffering {68            cmd.output()69        } else {70            // If running on only one thread, don't buffer output71            // Allows for viewing and interacting with intermediate command output72            cmd.spawn().and_then(|c| c.wait_with_output())73        };7475        // Then wait for the command to exit, if it was spawned.76        match output {77            Ok(output) => {78                if enable_output_buffering {79                    output_buffer.push(output.stdout, output.stderr);80                }81                if output.status.code() != Some(0) {82                    output_buffer.write();83                    return ExitCode::GeneralError;84                }85            }86            Err(why) => {87                output_buffer.write();88                return handle_cmd_error(Some(&cmd), why);89            }90        }91    }92    output_buffer.write();93    ExitCode::Success94}9596pub fn handle_cmd_error(cmd: Option<&Command>, err: io::Error) -> ExitCode {97    match (cmd, err) {98        (Some(cmd), err) if err.kind() == io::ErrorKind::NotFound => {99            print_error(format!(100                "Command not found: {}",101                cmd.get_program().to_string_lossy()102            ));103            ExitCode::GeneralError104        }105        (_, err) => {106            print_error(format!("Problem while executing command: {err}"));107            ExitCode::GeneralError108        }109    }110}