shell.rs
This file
Path
src/shell.rs
88 lines · 2.1 KiB · Rust
Last changed by
Add environment randomization on WindowsDavid Peterbefore adoption197e5df
History of this fileTake 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}2021fn randomized_environment_offset_value() -> String {22 "X".repeat(rand::random::<usize>() % 4096usize)23}2425/// Execute the given command and return a timing summary26#[cfg(not(windows))]27pub fn execute_and_time(28 stdout: Stdio,29 stderr: Stdio,30 command: &str,31 shell: &Shell,32) -> Result<ExecuteResult> {33 let cpu_timer = get_cpu_timer();3435 let status = shell36 .command()37 .arg("-c")38 .arg(command)39 .env(40 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",41 randomized_environment_offset_value(),42 )43 .stdin(Stdio::null())44 .stdout(stdout)45 .stderr(stderr)46 .status()47 .with_context(|| format!("Failed to run command '{}'", command))?;4849 let (user_time, system_time) = cpu_timer.stop();5051 Ok(ExecuteResult {52 user_time,53 system_time,54 status,55 })56}5758/// Execute the given command and return a timing summary59#[cfg(windows)]60pub fn execute_and_time(61 stdout: Stdio,62 stderr: Stdio,63 command: &str,64 shell: &Shell,65) -> Result<ExecuteResult> {66 let mut child = shell67 .command()68 .arg("/C")69 .arg(command)70 .env(71 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",72 randomized_environment_offset_value(),73 )74 .stdin(Stdio::null())75 .stdout(stdout)76 .stderr(stderr)77 .spawn()78 .with_context(|| format!("Failed to run command '{}'", command))?;79 let cpu_timer = get_cpu_timer(&child);80 let status = child.wait()?;8182 let (user_time, system_time) = cpu_timer.stop();83 Ok(ExecuteResult {84 user_time,85 system_time,86 status,87 })88}