Skip to content
Myr

command.rs

This file

Path

src/exec/command.rs

115 lines · 3.3 KiB · Rust

Last changed by

Merge pull request #1805 from tmccombs/exec-nulsThayne McCombsbefore adoption5558e40

History of this file

Take it

1use std::io;2use std::io::Write;34use argmax::Command;56use crate::error::print_error;7use crate::exit_codes::ExitCode;89struct Outputs {10    stdout: Vec<u8>,11    stderr: Vec<u8>,12}13pub struct OutputBuffer {14    null_separator: bool,15    outputs: Vec<Outputs>,16}1718impl OutputBuffer {19    pub fn new(null_separator: bool) -> Self {20        Self {21            null_separator,22            outputs: Vec::new(),23        }24    }2526    fn push(&mut self, stdout: Vec<u8>, stderr: Vec<u8>) {27        self.outputs.push(Outputs { stdout, stderr });28    }2930    fn write(self) {31        // Avoid taking the lock if there is nothing to do.32        // If null_separator is true, then we still need to write the33        // null separator, because the output may have been written directly34        // to stdout35        if self.outputs.is_empty() && !self.null_separator {36            return;37        }3839        let stdout = io::stdout();40        let stderr = io::stderr();4142        // While we hold these locks, only this thread will be able43        // to write its outputs.44        let mut stdout = stdout.lock();45        let mut stderr = stderr.lock();4647        for output in self.outputs.iter() {48            let _ = stdout.write_all(&output.stdout);49            let _ = stderr.write_all(&output.stderr);50        }51        if self.null_separator {52            // If null_separator is enabled, then we should write a \0 at the end53            // of the output for this entry54            let _ = stdout.write_all(b"\0");55        }56    }57}5859/// Executes a command.60pub fn execute_commands<I: Iterator<Item = io::Result<Command>>>(61    cmds: I,62    mut output_buffer: OutputBuffer,63    enable_output_buffering: bool,64) -> ExitCode {65    for result in cmds {66        let mut cmd = match result {67            Ok(cmd) => cmd,68            Err(e) => return handle_cmd_error(None, e),69        };7071        // Spawn the supplied command.72        let output = if enable_output_buffering {73            cmd.output()74        } else {75            // If running on only one thread, don't buffer output76            // Allows for viewing and interacting with intermediate command output77            cmd.spawn().and_then(|c| c.wait_with_output())78        };7980        // Then wait for the command to exit, if it was spawned.81        match output {82            Ok(output) => {83                if enable_output_buffering {84                    output_buffer.push(output.stdout, output.stderr);85                }86                if output.status.code() != Some(0) {87                    output_buffer.write();88                    return ExitCode::GeneralError;89                }90            }91            Err(why) => {92                output_buffer.write();93                return handle_cmd_error(Some(&cmd), why);94            }95        }96    }97    output_buffer.write();98    ExitCode::Success99}100101pub fn handle_cmd_error(cmd: Option<&Command>, err: io::Error) -> ExitCode {102    match (cmd, err) {103        (Some(cmd), err) if err.kind() == io::ErrorKind::NotFound => {104            print_error(format!(105                "Command not found: {}",106                cmd.get_program().to_string_lossy()107            ));108            ExitCode::GeneralError109        }110        (_, err) => {111            print_error(format!("Problem while executing command: {err}"));112            ExitCode::GeneralError113        }114    }115}