Skip to content
Myr

shell.rs

This file

Path

src/shell.rs

99 lines · 2.2 KiB · Rust

Last changed by

Parse --shell option value as shell commandrhysdbefore adoptione2fdace

History of this file

Take it

1use std::io;2use std::process::{ExitStatus, Stdio};34use crate::options::Shell;5use crate::timer::get_cpu_timer;67/// Used to indicate the result of running a command8#[derive(Debug, Copy, Clone)]9pub struct ExecuteResult {10    /// The amount of user time the process used11    pub user_time: f64,1213    /// The amount of cpu time the process used14    pub system_time: f64,1516    /// The exit status of the process17    pub status: ExitStatus,18}1920/// Execute the given command and return a timing summary21#[cfg(windows)]22pub fn execute_and_time(23    stdout: Stdio,24    stderr: Stdio,25    command: &str,26    shell: &Shell,27) -> io::Result<ExecuteResult> {28    let mut child = run_shell_command(stdout, stderr, command, shell)?;29    let cpu_timer = get_cpu_timer(&child);30    let status = child.wait()?;3132    let (user_time, system_time) = cpu_timer.stop();33    Ok(ExecuteResult {34        user_time,35        system_time,36        status,37    })38}3940/// Execute the given command and return a timing summary41#[cfg(not(windows))]42pub fn execute_and_time(43    stdout: Stdio,44    stderr: Stdio,45    command: &str,46    shell: &Shell,47) -> io::Result<ExecuteResult> {48    let cpu_timer = get_cpu_timer();4950    let status = run_shell_command(stdout, stderr, command, shell)?;5152    let (user_time, system_time) = cpu_timer.stop();5354    Ok(ExecuteResult {55        user_time,56        system_time,57        status,58    })59}6061/// Run a standard shell command using `sh -c`62#[cfg(not(windows))]63fn run_shell_command(64    stdout: Stdio,65    stderr: Stdio,66    command: &str,67    shell: &Shell,68) -> io::Result<std::process::ExitStatus> {69    shell70        .command()71        .arg("-c")72        .arg(command)73        .env(74            "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",75            "X".repeat(rand::random::<usize>() % 4096usize),76        )77        .stdin(Stdio::null())78        .stdout(stdout)79        .stderr(stderr)80        .status()81}8283/// Run a Windows shell command using `cmd.exe /C`84#[cfg(windows)]85fn run_shell_command(86    stdout: Stdio,87    stderr: Stdio,88    command: &str,89    shell: &Shell,90) -> io::Result<std::process::Child> {91    shell92        .command()93        .arg("/C")94        .arg(command)95        .stdin(Stdio::null())96        .stdout(stdout)97        .stderr(stderr)98        .spawn()99}