Skip to content
Myr

command.rs

This file

Path

src/exec/command.rs

52 lines · 1.6 KiB · Rust

Last changed by

Address feedback for removing buffering when running on a single threadThayne McCombsbefore adoptione473060

History of this file

Take it

1use std::io;2use std::io::Write;3use std::process::Command;4use std::sync::Mutex;56use crate::error::print_error;7use crate::exit_codes::ExitCode;89/// Executes a command.10pub fn execute_command(11    mut cmd: Command,12    out_perm: &Mutex<()>,13    enable_output_buffering: bool,14) -> ExitCode {15    // Spawn the supplied command.16    let output = if enable_output_buffering {17        cmd.output()18    } else {19        // If running on only one thread, don't buffer output20        // Allows for viewing and interacting with intermediate command output21        cmd.spawn().and_then(|c| c.wait_with_output())22    };2324    // Then wait for the command to exit, if it was spawned.25    match output {26        Ok(output) => {27            // While this lock is active, this thread will be the only thread allowed28            // to write its outputs.29            let _lock = out_perm.lock().unwrap();3031            let stdout = io::stdout();32            let stderr = io::stderr();3334            let _ = stdout.lock().write_all(&output.stdout);35            let _ = stderr.lock().write_all(&output.stderr);3637            if output.status.code() == Some(0) {38                ExitCode::Success39            } else {40                ExitCode::GeneralError41            }42        }43        Err(ref why) if why.kind() == io::ErrorKind::NotFound => {44            print_error(format!("Command not found: {:?}", cmd));45            ExitCode::GeneralError46        }47        Err(why) => {48            print_error(format!("Problem while executing command: {}", why));49            ExitCode::GeneralError50        }51    }52}