Skip to content
Myr

command.rs

This file

Path

src/exec/command.rs

114 lines · 3.3 KiB · Rust

Last changed by

fix: Better sanitizingThayne McCombsbefore adoption24198d9

History of this file

Take it

1use std::io;2use std::io::Write;34use argmax::Command;56use crate::exit_codes::ExitCode;78struct Outputs {9    stdout: Vec<u8>,10    stderr: Vec<u8>,11}12pub struct OutputBuffer {13    null_separator: bool,14    outputs: Vec<Outputs>,15}1617impl OutputBuffer {18    pub fn new(null_separator: bool) -> Self {19        Self {20            null_separator,21            outputs: Vec::new(),22        }23    }2425    fn push(&mut self, stdout: Vec<u8>, stderr: Vec<u8>) {26        self.outputs.push(Outputs { stdout, stderr });27    }2829    fn write(self) {30        // Avoid taking the lock if there is nothing to do.31        // If null_separator is true, then we still need to write the32        // null separator, because the output may have been written directly33        // to stdout34        if self.outputs.is_empty() && !self.null_separator {35            return;36        }3738        let stdout = io::stdout();39        let stderr = io::stderr();4041        // While we hold these locks, only this thread will be able42        // to write its outputs.43        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        if self.null_separator {51            // If null_separator is enabled, then we should write a \0 at the end52            // of the output for this entry53            let _ = stdout.write_all(b"\0");54        }55    }56}5758/// Executes a command.59pub fn execute_commands<I: Iterator<Item = io::Result<Command>>>(60    cmds: I,61    mut output_buffer: OutputBuffer,62    enable_output_buffering: bool,63) -> ExitCode {64    for result in cmds {65        let mut cmd = match result {66            Ok(cmd) => cmd,67            Err(e) => return handle_cmd_error(None, e),68        };6970        // Spawn the supplied command.71        let output = if enable_output_buffering {72            cmd.output()73        } else {74            // If running on only one thread, don't buffer output75            // Allows for viewing and interacting with intermediate command output76            cmd.spawn().and_then(|c| c.wait_with_output())77        };7879        // Then wait for the command to exit, if it was spawned.80        match output {81            Ok(output) => {82                if enable_output_buffering {83                    output_buffer.push(output.stdout, output.stderr);84                }85                if output.status.code() != Some(0) {86                    output_buffer.write();87                    return ExitCode::GeneralError;88                }89            }90            Err(why) => {91                output_buffer.write();92                return handle_cmd_error(Some(&cmd), why);93            }94        }95    }96    output_buffer.write();97    ExitCode::Success98}99100pub fn handle_cmd_error(cmd: Option<&Command>, err: io::Error) -> ExitCode {101    match (cmd, err) {102        (Some(cmd), err) if err.kind() == io::ErrorKind::NotFound => {103            print_error!(104                "Command not found: {:?}",105                cmd.get_program().to_string_lossy().as_ref()106            );107            ExitCode::GeneralError108        }109        (_, err) => {110            print_error!("Problem while executing command: {}", err);111            ExitCode::GeneralError112        }113    }114}