options.rs
This file
Path
src/options.rs
399 lines · 11.6 KiB · Rust
Last changed by
Address review commentsTavian Barnesbefore adoption3df63ba
History of this fileTake it
1use std::fs::File;2use std::path::PathBuf;3use std::process::{Command, Stdio};4use std::{cmp, fmt, io};56use anyhow::ensure;7use atty::Stream;8use clap::ArgMatches;910use crate::command::Commands;11use crate::error::OptionsError;12use crate::util::units::{Second, Unit};1314use anyhow::Result;1516#[cfg(not(windows))]17pub const DEFAULT_SHELL: &str = "sh";1819#[cfg(windows)]20pub const DEFAULT_SHELL: &str = "cmd.exe";2122/// Shell to use for executing benchmarked commands23#[derive(Debug)]24pub enum Shell {25 /// Default shell command26 Default(&'static str),2728 /// Custom shell command specified via --shell29 Custom(Vec<String>),30}3132impl Default for Shell {33 fn default() -> Self {34 Shell::Default(DEFAULT_SHELL)35 }36}3738impl fmt::Display for Shell {39 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {40 match self {41 Shell::Default(cmd) => write!(f, "{}", cmd),42 Shell::Custom(cmdline) => write!(f, "{}", shell_words::join(cmdline)),43 }44 }45}4647impl Shell {48 /// Parse given string as shell command line49 pub fn parse_from_str<'a>(s: &str) -> Result<Self, OptionsError<'a>> {50 let v = shell_words::split(s).map_err(OptionsError::ShellParseError)?;51 if v.is_empty() || v[0].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 message73 RaiseError,7475 /// Simply ignore the non-zero exit code76 Ignore,77}7879/// Output style type option80#[derive(Debug, Clone, Copy, PartialEq)]81pub enum OutputStyleOption {82 /// Do not output with colors or any special formatting83 Basic,8485 /// Output with full color and formatting86 Full,8788 /// Keep elements such as progress bar, but use no coloring89 NoColor,9091 /// Keep coloring, but use no progress bar92 Color,9394 /// Disable all the output95 Disabled,96}9798/// Bounds for the number of benchmark runs99pub struct RunBounds {100 /// Minimum number of benchmark runs101 pub min: u64,102103 /// Maximum number of benchmark runs104 pub max: Option<u64>,105}106107impl Default for RunBounds {108 fn default() -> Self {109 RunBounds { min: 10, max: None }110 }111}112113/// How to handle the output of benchmarked commands114#[derive(Debug, Clone, PartialEq)]115pub enum CommandOutputPolicy {116 /// Redirect output to the null device117 Null,118119 /// Feed output through a pipe before discarding it120 Pipe,121122 /// Redirect output to a file123 File(PathBuf),124125 /// Show command output on the terminal126 Inherit,127}128129impl Default for CommandOutputPolicy {130 fn default() -> Self {131 CommandOutputPolicy::Null132 }133}134135impl CommandOutputPolicy {136 pub fn get_stdout_stderr(&self) -> io::Result<(Stdio, Stdio)> {137 let streams = match self {138 CommandOutputPolicy::Null => (Stdio::null(), Stdio::null()),139140 // Typically only stdout is performance-relevant, so just pipe that141 CommandOutputPolicy::Pipe => (Stdio::piped(), Stdio::null()),142143 CommandOutputPolicy::File(path) => {144 let file = File::create(&path)?;145 (file.into(), Stdio::null())146 }147148 CommandOutputPolicy::Inherit => (Stdio::inherit(), Stdio::inherit()),149 };150151 Ok(streams)152 }153}154155pub enum ExecutorKind {156 Raw,157 Shell(Shell),158 Mock(Option<String>),159}160161impl Default for ExecutorKind {162 fn default() -> Self {163 ExecutorKind::Shell(Shell::default())164 }165}166167/// The main settings for a hyperfine benchmark session168pub struct Options {169 /// Upper and lower bound for the number of benchmark runs170 pub run_bounds: RunBounds,171172 /// Number of warmup runs173 pub warmup_count: u64,174175 /// Minimum benchmarking time176 pub min_benchmarking_time: Second,177178 /// Whether or not to ignore non-zero exit codes179 pub command_failure_action: CmdFailureAction,180181 /// Command(s) to run before each timing run182 pub preparation_command: Option<Vec<String>>,183184 /// Command to run before each *batch* of timing runs, i.e. before each individual benchmark185 pub setup_command: Option<String>,186187 /// Command to run after each *batch* of timing runs, i.e. after each individual benchmark188 pub cleanup_command: Option<String>,189190 /// What color mode to use for the terminal output191 pub output_style: OutputStyleOption,192193 /// Determines how we run commands194 pub executor_kind: ExecutorKind,195196 /// What to do with the output of the benchmarked command197 pub command_output_policy: CommandOutputPolicy,198199 /// Which time unit to use when displaying resuls200 pub time_unit: Option<Unit>,201}202203impl Default for Options {204 fn default() -> Options {205 Options {206 run_bounds: RunBounds::default(),207 warmup_count: 0,208 min_benchmarking_time: 3.0,209 command_failure_action: CmdFailureAction::RaiseError,210 preparation_command: None,211 setup_command: None,212 cleanup_command: None,213 output_style: OutputStyleOption::Full,214 executor_kind: ExecutorKind::default(),215 command_output_policy: CommandOutputPolicy::Null,216 time_unit: None,217 }218 }219}220221impl Options {222 pub fn from_cli_arguments<'a>(matches: &ArgMatches) -> Result<Self, OptionsError<'a>> {223 let mut options = Self::default();224 let param_to_u64 = |param| {225 matches226 .value_of(param)227 .map(|n| {228 n.parse::<u64>()229 .map_err(|e| OptionsError::NumericParsingError(param, e))230 })231 .transpose()232 };233234 options.warmup_count = param_to_u64("warmup")?.unwrap_or(options.warmup_count);235236 let mut min_runs = param_to_u64("min-runs")?;237 let mut max_runs = param_to_u64("max-runs")?;238239 if let Some(runs) = param_to_u64("runs")? {240 min_runs = Some(runs);241 max_runs = Some(runs);242 }243244 match (min_runs, max_runs) {245 (Some(min), None) => {246 options.run_bounds.min = min;247 }248 (None, Some(max)) => {249 // Since the minimum was not explicit we lower it if max is below the default min.250 options.run_bounds.min = cmp::min(options.run_bounds.min, max);251 options.run_bounds.max = Some(max);252 }253 (Some(min), Some(max)) if min > max => {254 return Err(OptionsError::EmptyRunsRange);255 }256 (Some(min), Some(max)) => {257 options.run_bounds.min = min;258 options.run_bounds.max = Some(max);259 }260 (None, None) => {}261 };262263 options.setup_command = matches.value_of("setup").map(String::from);264265 options.preparation_command = matches266 .values_of("prepare")267 .map(|values| values.map(String::from).collect::<Vec<String>>());268269 options.cleanup_command = matches.value_of("cleanup").map(String::from);270271 options.command_output_policy = if matches.is_present("show-output") {272 CommandOutputPolicy::Inherit273 } else if let Some(output) = matches.value_of("output") {274 match output {275 "null" => CommandOutputPolicy::Null,276 "pipe" => CommandOutputPolicy::Pipe,277 "inherit" => CommandOutputPolicy::Inherit,278 arg => {279 let path = PathBuf::from(arg);280 if path.components().count() <= 1 {281 return Err(OptionsError::UnknownOutputPolicy(arg.to_string()));282 }283 CommandOutputPolicy::File(path)284 }285 }286 } else {287 CommandOutputPolicy::Null288 };289290 options.output_style = match matches.value_of("style") {291 Some("full") => OutputStyleOption::Full,292 Some("basic") => OutputStyleOption::Basic,293 Some("nocolor") => OutputStyleOption::NoColor,294 Some("color") => OutputStyleOption::Color,295 Some("none") => OutputStyleOption::Disabled,296 _ => {297 if options.command_output_policy == CommandOutputPolicy::Inherit298 || !atty::is(Stream::Stdout)299 {300 OutputStyleOption::Basic301 } else {302 OutputStyleOption::Full303 }304 }305 };306307 match options.output_style {308 OutputStyleOption::Basic | OutputStyleOption::NoColor => {309 colored::control::set_override(false)310 }311 OutputStyleOption::Full | OutputStyleOption::Color => {312 colored::control::set_override(true)313 }314 OutputStyleOption::Disabled => {}315 };316317 options.executor_kind = if matches.is_present("no-shell") {318 ExecutorKind::Raw319 } else {320 match (matches.is_present("debug-mode"), matches.value_of("shell")) {321 (false, Some(shell)) if shell == "default" => ExecutorKind::Shell(Shell::default()),322 (false, Some(shell)) if shell == "none" => ExecutorKind::Raw,323 (false, Some(shell)) => ExecutorKind::Shell(Shell::parse_from_str(shell)?),324 (false, None) => ExecutorKind::Shell(Shell::default()),325 (true, Some(shell)) => ExecutorKind::Mock(Some(shell.into())),326 (true, None) => ExecutorKind::Mock(None),327 }328 };329330 if matches.is_present("ignore-failure") {331 options.command_failure_action = CmdFailureAction::Ignore;332 }333334 options.time_unit = match matches.value_of("time-unit") {335 Some("millisecond") => Some(Unit::MilliSecond),336 Some("second") => Some(Unit::Second),337 _ => None,338 };339340 Ok(options)341 }342343 pub fn validate_against_command_list(&self, commands: &Commands) -> Result<()> {344 if let Some(preparation_command) = &self.preparation_command {345 ensure!(346 preparation_command.len() <= 1347 || commands.num_commands() == preparation_command.len(),348 "The '--prepare' option has to be provided just once or N times, where N is the \349 number of benchmark commands."350 );351 }352353 Ok(())354 }355}356357#[test]358fn test_default_shell() {359 let shell = Shell::default();360361 let s = format!("{}", shell);362 assert_eq!(&s, DEFAULT_SHELL);363364 let cmd = shell.command();365 assert_eq!(cmd.get_program(), DEFAULT_SHELL);366}367368#[test]369fn test_can_parse_shell_command_line_from_str() {370 let shell = Shell::parse_from_str("shell -x 'aaa bbb'").unwrap();371372 let s = format!("{}", shell);373 assert_eq!(&s, "shell -x 'aaa bbb'");374375 let cmd = shell.command();376 assert_eq!(cmd.get_program().to_string_lossy(), "shell");377 assert_eq!(378 cmd.get_args()379 .map(|a| a.to_string_lossy())380 .collect::<Vec<_>>(),381 vec!["-x", "aaa bbb"]382 );383384 // Error cases385 assert!(matches!(386 Shell::parse_from_str("shell 'foo").unwrap_err(),387 OptionsError::ShellParseError(_)388 ));389390 assert!(matches!(391 Shell::parse_from_str("").unwrap_err(),392 OptionsError::EmptyShell393 ));394395 assert!(matches!(396 Shell::parse_from_str("''").unwrap_err(),397 OptionsError::EmptyShell398 ));399}