Skip to content
Myr

Parse --shell option value as shell command

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by rhysd · committed by David Peter · parent 5c6879e · Browse files · 7 files+96 added−20 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+96 added−20 removed

  • other:+96 added−20 removed

7 files+96 added−20 removed

modified:src/benchmark.rs+6 added-6 removed
7 unmodified lines
8use crate::benchmark_result::BenchmarkResult;9use crate::command::Command;10use crate::format::{format_duration, format_duration_unit};11use crate::min_max::{max, min};12use crate::options::{CmdFailureAction, HyperfineOptions, OutputStyleOption};12use crate::options::{CmdFailureAction, HyperfineOptions, OutputStyleOption, Shell};13use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};14use crate::progress_bar::get_progress_bar;15use crate::shell::execute_and_time;16use crate::timer::wallclocktimer::WallClockTimer;
27 unmodified lines
44}4546/// Run the given shell command and measure the execution time47pub fn time_shell_command(48 shell: &str,48 shell: &Shell,49 command: &Command<'_>,50 show_output: bool,51 failure_action: CmdFailureAction,52 shell_spawning_time: Option<TimingResult>,
44 unmodified lines
97}9899/// Measure the average shell spawning time100pub fn mean_shell_spawning_time(101 shell: &str,101 shell: &Shell,102 style: OutputStyleOption,103 show_output: bool,104) -> io::Result<TimingResult> {105 const COUNT: u64 = 50;
61 unmodified lines
167 })168}169170fn run_intermediate_command(171 shell: &str,171 shell: &Shell,172 command: &Option<Command<'_>>,173 show_output: bool,174 error_output: &'static str,175) -> io::Result<TimingResult> {
10 unmodified lines
186}187188/// Run the command specified by `--prepare`.189fn run_preparation_command(190 shell: &str,190 shell: &Shell,191 command: &Option<Command<'_>>,192 show_output: bool,193) -> io::Result<TimingResult> {194 let error_output = "The preparation command terminated with a non-zero exit code. \
3 unmodified lines
198}199200/// Run the command specified by `--cleanup`.201fn run_cleanup_command(202 shell: &str,202 shell: &Shell,203 command: &Option<Command<'_>>,204 show_output: bool,205) -> io::Result<TimingResult> {206 let error_output = "The cleanup command terminated with a non-zero exit code. \
282 unmodified lines
modified:src/error.rs+6 added
60 unmodified lines
61 EmptyRunsRange,62 TooManyCommandNames(usize),63 UnexpectedCommandNameCount(usize, usize),64 NumericParsingError(&'a str, ParseIntError),65 EmptyShell,66 ShellParseError(shell_words::ParseError),67}6869impl<'a> fmt::Display for OptionsError<'a> {70 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
15 unmodified lines
86 "Could not read numeric argument to '--{cmd}': {err}",87 cmd = cmd,88 err = err89 ),90 OptionsError::EmptyShell => write!(f, "Empty command at --shell option"),91 OptionsError::ShellParseError(ref err) => {92 write!(f, "Could not parse --shell value as command line: {}", err)93 }94 }95 }96}97
1 unmodified line
modified:src/main.rs+4 added-5 removed
31 unmodified lines
32use benchmark_result::BenchmarkResult;33use command::Command;34use error::OptionsError;35use export::{ExportManager, ExportType};36use options::{CmdFailureAction, HyperfineOptions, OutputStyleOption};36use options::{CmdFailureAction, HyperfineOptions, OutputStyleOption, Shell};37use parameter_range::get_parameterized_commands;38use tokenize::tokenize;39use types::ParameterValue;40use units::Unit;
187 unmodified lines
228 OutputStyleOption::Full | OutputStyleOption::Color => colored::control::set_override(true),229 OutputStyleOption::Disabled => {}230 };231232 options.shell = matches233 .value_of("shell")234 .unwrap_or(&options.shell)235 .to_string();232 if let Some(shell) = matches.value_of("shell") {233 options.shell = Shell::parse(shell)?;234 }235236 if matches.is_present("ignore-failure") {237 options.failure_action = CmdFailureAction::Ignore;238 }
221 unmodified lines
modified:src/options.rs+62 added-2 removed
1use std::fmt;2use std::process::Command;34use crate::error::OptionsError;5use crate::units::{Second, Unit};67#[cfg(not(windows))]8pub const DEFAULT_SHELL: &str = "sh";910#[cfg(windows)]11pub const DEFAULT_SHELL: &str = "cmd.exe";1213/// Shell to use for executing benchmarked commands14pub enum Shell {15 /// Default shell command16 Default(&'static str),17 /// Custom shell command specified via --shell18 Custom(Vec<String>),19}2021impl Default for Shell {22 fn default() -> Self {23 Shell::Default(DEFAULT_SHELL)24 }25}2627impl fmt::Display for Shell {28 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {29 match self {30 Shell::Default(cmd) => write!(f, "{}", cmd),31 Shell::Custom(cmdline) => {32 let mut first = true;33 for s in cmdline.iter() {34 if first {35 first = false;36 write!(f, "{}", s)?;37 } else {38 write!(f, " {}", s)?;39 }40 }41 Ok(())42 }43 }44 }45}4647impl Shell {48 /// Parse given string as shell command line49 pub fn parse<'a>(s: &str) -> Result<Self, OptionsError<'a>> {50 let v = shell_words::split(s.as_ref()).map_err(OptionsError::ShellParseError)?;51 if v.is_empty() {52 return Err(OptionsError::EmptyShell);53 }54 Ok(Shell::Custom(v))55 }5657 pub fn command(&self) -> Command {58 match self {59 Shell::Default(cmd) => Command::new(cmd),60 Shell::Custom(cmdline) => {61 let mut c = Command::new(&cmdline[0]);62 c.args(&cmdline[1..]);63 c64 }65 }66 }67}6869/// Action to take when an executed command fails.70#[derive(Debug, Clone, Copy, PartialEq)]71pub enum CmdFailureAction {72 /// Exit with an error message
60 unmodified lines
133 /// What color mode to use for output134 pub output_style: OutputStyleOption,135136 /// The shell to use for executing commands.77 pub shell: String,137 pub shell: Shell,138139 /// Forward benchmark's stdout to hyperfine's stdout140 pub show_output: bool,141
16 unmodified lines
158 failure_action: CmdFailureAction::RaiseError,159 preparation_command: None,160 cleanup_command: None,161 output_style: OutputStyleOption::Full,102 shell: DEFAULT_SHELL.to_string(),162 shell: Shell::default(),163 show_output: false,164 time_unit: None,165 }166 }
1 unmodified line
modified:src/shell.rs+10 added-7 removed
1use std::io;2use std::process::{Command, ExitStatus, Stdio};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)]
13 unmodified lines
22pub fn execute_and_time(23 stdout: Stdio,24 stderr: Stdio,25 command: &str,25 shell: &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()?;
11 unmodified lines
42pub fn execute_and_time(43 stdout: Stdio,44 stderr: Stdio,45 command: &str,45 shell: &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)?;
12 unmodified lines
63fn run_shell_command(64 stdout: Stdio,65 stderr: Stdio,66 command: &str,66 shell: &str,67 shell: &Shell,68) -> io::Result<std::process::ExitStatus> {68 Command::new(shell)69 shell70 .command()71 .arg("-c")72 .arg(command)73 .env(74 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",
10 unmodified lines
85fn run_shell_command(86 stdout: Stdio,87 stderr: Stdio,88 command: &str,87 shell: &str,89 shell: &Shell,90) -> io::Result<std::process::Child> {89 Command::new(shell)91 shell92 .command()93 .arg("/C")94 .arg(command)95 .stdin(Stdio::null())96 .stdout(stdout)
3 unmodified lines
modified:Cargo.lock+7 added
241 unmodified lines
242 "rand 0.8.4",243 "rust_decimal",244 "serde",245 "serde_json",246 "shell-words",247 "statistical",248 "tempfile",249 "winapi",250]
430 unmodified lines
681 "serde",682]683684[[package]]685name = "shell-words"686version = "1.0.0"687source = "registry+https://github.com/rust-lang/crates.io-index"688checksum = "b6fa3938c99da4914afedd13bf3d79bcb6c277d1b2c398d23257a304d9e1b074"689690[[package]]691name = "statistical"692version = "1.0.0"693source = "registry+https://github.com/rust-lang/crates.io-index"694checksum = "49d57902bb128e5e38b5218d3681215ae3e322d99f65d5420e9849730d2ea372"
126 unmodified lines
modified:Cargo.toml+1 added