Skip to content
Myr

shell.rs

This file

Path

src/shell.rs

102 lines · 2.4 KiB · Rust

Last changed by

Fix Windows codeDavid Peterbefore adoptionc4ae7f6

History of this file

Take it

1use std::process::{ExitStatus, Stdio};23use crate::options::Shell;4use crate::timer::get_cpu_timer;56use anyhow::{Context, Result};78/// Used to indicate the result of running a command9#[derive(Debug, Copy, Clone)]10pub struct ExecuteResult {11    /// The amount of user time the process used12    pub user_time: f64,1314    /// The amount of cpu time the process used15    pub system_time: f64,1617    /// The exit status of the process18    pub status: ExitStatus,19}2021/// Execute the given command and return a timing summary22#[cfg(windows)]23pub fn execute_and_time(24    stdout: Stdio,25    stderr: Stdio,26    command: &str,27    shell: &Shell,28) -> Result<ExecuteResult> {29    let mut child = run_shell_command(stdout, stderr, command, shell)?;30    let cpu_timer = get_cpu_timer(&child);31    let status = child.wait()?;3233    let (user_time, system_time) = cpu_timer.stop();34    Ok(ExecuteResult {35        user_time,36        system_time,37        status,38    })39}4041/// Execute the given command and return a timing summary42#[cfg(not(windows))]43pub fn execute_and_time(44    stdout: Stdio,45    stderr: Stdio,46    command: &str,47    shell: &Shell,48) -> Result<ExecuteResult> {49    let cpu_timer = get_cpu_timer();5051    let status = run_shell_command(stdout, stderr, command, shell)?;5253    let (user_time, system_time) = cpu_timer.stop();5455    Ok(ExecuteResult {56        user_time,57        system_time,58        status,59    })60}6162/// Run a standard shell command using `sh -c`63#[cfg(not(windows))]64fn run_shell_command(65    stdout: Stdio,66    stderr: Stdio,67    command: &str,68    shell: &Shell,69) -> Result<std::process::ExitStatus> {70    shell71        .command()72        .arg("-c")73        .arg(command)74        .env(75            "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",76            "X".repeat(rand::random::<usize>() % 4096usize),77        )78        .stdin(Stdio::null())79        .stdout(stdout)80        .stderr(stderr)81        .status()82        .with_context(|| format!("Failed to run command '{}'", command))83}8485/// Run a Windows shell command using `cmd.exe /C`86#[cfg(windows)]87fn run_shell_command(88    stdout: Stdio,89    stderr: Stdio,90    command: &str,91    shell: &Shell,92) -> Result<std::process::Child> {93    shell94        .command()95        .arg("/C")96        .arg(command)97        .stdin(Stdio::null())98        .stdout(stdout)99        .stderr(stderr)100        .spawn()101        .with_context(|| format!("Failed to run command '{}'", command))102}