Skip to content
Myr

command.rs

This file

Path

src/exec/command.rs

50 lines · 1.6 KiB · Rust

Last changed by

Clarifying commentsMax Trianobefore adoption154cd6e

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(mut cmd: Command, out_perm: &Mutex<()>, is_multithread: bool) -> ExitCode {11    let output;12    // Spawn the supplied command.13    if is_multithread {14        output = cmd.output();15    } else {16        // If running on only one thread, don't buffer output17        // Allows for viewing and interacting with intermediate command output18        let child = cmd.spawn().expect("Failed to execute command");19        output = child.wait_with_output();20    }21    22    // Then wait for the command to exit, if it was spawned.23    match output {24        Ok(output) => {25            // While this lock is active, this thread will be the only thread allowed26            // to write its outputs.27            let _lock = out_perm.lock().unwrap();2829            let stdout = io::stdout();30            let stderr = io::stderr();3132            let _ = stdout.lock().write_all(&output.stdout);33            let _ = stderr.lock().write_all(&output.stderr);3435            if output.status.code() == Some(0) {36                ExitCode::Success37            } else {38                ExitCode::GeneralError39            }40        }41        Err(ref why) if why.kind() == io::ErrorKind::NotFound => {42            print_error(format!("Command not found: {:?}", cmd));43            ExitCode::GeneralError44        }45        Err(why) => {46            print_error(format!("Problem while executing command: {}", why));47            ExitCode::GeneralError48        }49    }50}